"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 LocalePageShell from "@/components/i18n/LocalePageShell";
import { ExploreFilterId } from "@/constants/exploreFilters";
import { getSeoPage } from "@/lib/i18n/seo";
import { useAppLanguage } from "@/contexts/LanguageProvider";
import { useCallback, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

function parseSearchQuery(input: string): { q?: string; hashtag?: string } {
  const trimmed = input.trim();
  if (!trimmed) return {};
  if (trimmed.startsWith("#")) {
    const tag = trimmed.slice(1).trim();
    return tag ? { hashtag: tag } : {};
  }
  return { q: trimmed };
}

export default function ExplorePage() {
  const { t } = useTranslation("common");
  const { language } = useAppLanguage();
  const [activeFilter, setActiveFilter] = useState<ExploreFilterId>("all");
  const [coords, setCoords] = useState<{ lat: number; lng: number } | null>(
    null
  );
  const [loadingLocation, setLoadingLocation] = useState(false);
  const [searchInput, setSearchInput] = useState("");
  const [searchQuery, setSearchQuery] = useState<{
    q?: string;
    hashtag?: string;
  }>({});

  const handleSearchSubmit = useCallback((value?: string) => {
    const nextValue = value ?? searchInput;
    if (value !== undefined) setSearchInput(value);
    setSearchQuery(parseSearchQuery(nextValue));
  }, [searchInput]);

  const handleFilterChange = useCallback((filter: ExploreFilterId) => {
    if (filter === "near_me") {
      if (!navigator.geolocation) {
        toast.error(t("explore.geoNotSupported"));
        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(t("explore.geoPermissionRequired"));
        },
        { enableHighAccuracy: true, timeout: 15000 }
      );
      return;
    }

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

  const exploreSeo = getSeoPage("explore", language);

  return (
    <>
      <Header />
      <LocalePageShell>
        <Container className="pb-28">
          <h1 className="sr-only">{exploreSeo.title.split("|")[0].trim()}</h1>
          <div className="pb-2 pt-1">
            <ExploreFilterBar
              activeFilter={activeFilter}
              onFilterChange={handleFilterChange}
              loadingLocation={loadingLocation}
              searchValue={searchInput}
              onSearchChange={setSearchInput}
              onSearchSubmit={handleSearchSubmit}
            />
          </div>
          <ExploreGrid
            activeFilter={activeFilter}
            coords={coords}
            searchQuery={searchQuery}
          />
        </Container>
      </LocalePageShell>
      <TabNavigation currentPage="/explore" />
    </>
  );
}
