"use client";

import Container from "@/components/elements/Container";
import TabNavigation from "@/components/TabNavigation";
import ExploreFilterBar from "@/components/explore/ExploreFilterBar";
import ExploreGrid from "@/components/explore/ExploreGrid";
import Header from "@/components/main/Header";
import { ExploreFilterId } from "@/constants/exploreFilters";
import { pageSeo } from "@/config/pageSeo";
import { useCallback, useState } from "react";
import toast from "react-hot-toast";

export default function ExplorePage() {
  const [activeFilter, setActiveFilter] = useState<ExploreFilterId>("all");
  const [coords, setCoords] = useState<{ lat: number; lng: number } | null>(
    null
  );
  const [loadingLocation, setLoadingLocation] = useState(false);

  const handleFilterChange = useCallback((filter: ExploreFilterId) => {
    if (filter === "near_me") {
      if (!navigator.geolocation) {
        toast.error("مرورگر شما از موقعیت مکانی پشتیبانی نمی‌کند.");
        return;
      }

      setLoadingLocation(true);
      navigator.geolocation.getCurrentPosition(
        (position) => {
          setCoords({
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          });
          setActiveFilter("near_me");
          setLoadingLocation(false);
        },
        () => {
          setLoadingLocation(false);
          toast.error(
            "برای نمایش پست‌های نزدیک، دسترسی به موقعیت مکانی لازم است."
          );
        },
        { enableHighAccuracy: true, timeout: 15000 }
      );
      return;
    }

    setActiveFilter(filter);
    if (filter !== "near_me") {
      setCoords(null);
    }
  }, []);

  return (
    <>
      <Header />
      <Container className="pb-28">
        <h1 className="sr-only">
          {pageSeo.explore.title.replace(" | مدستاگرام", "")}
        </h1>
        <ExploreFilterBar
          activeFilter={activeFilter}
          onFilterChange={handleFilterChange}
          loadingLocation={loadingLocation}
        />
        <ExploreGrid activeFilter={activeFilter} coords={coords} />
      </Container>
      <TabNavigation currentPage="/explore" />
    </>
  );
}
