"use client";
import Image from "next/image";
import { useRouter, useParams, useSearchParams } from "next/navigation";
import React, { useState, useEffect } from "react";
import RoundedInput from "@/components/elements/RoundedInput";
import FilterModal from "./FilterModal";
import BoldIcon from "@/components/ui/BoldIcon";
import Link from "next/link";
import { useTranslation } from "react-i18next";
import provinces from "@/data/provinces.json";
import cities from "@/data/cities.json";

function BillboardsFilter() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const params = useParams();
  const searchParams = useSearchParams();

  const [showFilterModal, setShowFilterModal] = useState<boolean>(false);
  const [stateId, setStateId] = useState<string>("");
  const [cityId, setCityId] = useState<string>("");
  const [category, setCategory] = useState<string>("");
  const [sort, setSort] = useState<string>("");
  const [searchText, setSearchText] = useState<string>("");

  const slugPrefix = t("billboards.slug.prefix");
  const slugInWord = t("billboards.slug.inWord");
  const slugInCityLabel = t("billboards.slug.inCityLabel");
  const slugInProvinceLabel = t("billboards.slug.inProvinceLabel");
  const slugDefaultCategoryLabel = t("billboards.slug.defaultCategoryLabel");

  useEffect(() => {
    const slugSegments = params.slug as string[];
    if (slugSegments && slugSegments.length > 0) {
      const fullText = decodeURIComponent(slugSegments[0]).replace(/-/g, " ");

      if (fullText.startsWith(slugPrefix)) {
        const afterAds = fullText.split(slugPrefix)[1]?.trim();
        if (afterAds) {
          const extractedCat = afterAds.split(slugInWord)[0]?.trim();
          if (extractedCat && !extractedCat.includes(slugDefaultCategoryLabel)) {
            setCategory(extractedCat);
          }
        }

        if (fullText.includes(slugInCityLabel)) {
          const cityName = fullText.split(slugInCityLabel)[1]?.trim();
          const foundCity = cities.find((c) => cityName?.includes(c.name));
          if (foundCity) setCityId(foundCity.id.toString());
        } else if (fullText.includes(slugInProvinceLabel)) {
          const provinceName = fullText.split(slugInProvinceLabel)[1]?.trim();
          const foundProvince = provinces.find((p) =>
            provinceName?.includes(p.name)
          );
          if (foundProvince) setStateId(foundProvince.id.toString());
        }
      }
    }

    setSearchText(searchParams.get("search") || "");
    setSort(searchParams.get("sort") || "");
  }, [
    params,
    searchParams,
    slugPrefix,
    slugInWord,
    slugInCityLabel,
    slugInProvinceLabel,
    slugDefaultCategoryLabel,
  ]);

  const handleFilterChange = () => {
    const provinceObj = provinces.find((p) => String(p.id) === String(stateId));
    const cityObj = cities.find((c) => String(c.id) === String(cityId));

    const slugParts = [];

    if (category) {
      slugParts.push(`${slugPrefix}-${category.replace(/\s+/g, "-")}`);
    } else {
      slugParts.push(`${slugPrefix}-${t("billboards.slug.defaultCategory")}`);
    }

    if (cityObj) {
      slugParts.push(`${t("billboards.slug.inCity")}-${cityObj.name.replace(/\s+/g, "-")}`);
    } else if (provinceObj) {
      slugParts.push(
        `${t("billboards.slug.inProvince")}-${provinceObj.name.replace(/\s+/g, "-")}`
      );
    }

    const finalSlug = slugParts.join("-");

    const queryParams = new URLSearchParams();
    if (searchText) queryParams.set("search", searchText);
    if (sort) queryParams.set("sort", sort);

    const queryString = queryParams.toString();
    const finalPath = `/billboards/${encodeURIComponent(finalSlug)}`;

    router.push(`${finalPath}${queryString ? `?${queryString}` : ""}`);
    setShowFilterModal(false);
  };

  const clearFilters = () => {
    setStateId("");
    setCityId("");
    setCategory("");
    setSort("");
    setSearchText("");

    router.push("/billboards");
    setShowFilterModal(false);
  };

  return (
    <div>
      <div className="flex items-center justify-between relative text-sm gap-3">
        <div className="w-full relative">
          <RoundedInput
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && handleFilterChange()}
            placeholder={t("billboards.search")}
            className="w-full"
          />
          <Image
            onClick={() => handleFilterChange()}
            width={25}
            height={25}
            alt="search icon"
            src="/images/icons/search-normal.svg"
            className=" min-w-[25px] absolute left-3 top-[7px] cursor-pointer"
          />
        </div>
        <div className="flex items-center gap-3">
          <button onClick={() => setShowFilterModal(true)}>
            <Image
              width={25}
              height={25}
              alt="filter icon"
              src="/images/icons/candle.svg"
              className="dark:invert min-w-[25px]"
            />
          </button>
          <Link href="/billboards/new" aria-label={t("billboards.createAria")}>
            <BoldIcon
              name="add-square"
              size={25}
              tinted
              className="text-neutral-700 dark:text-neutral-200 min-w-[25px]"
            />
          </Link>
        </div>
      </div>
      {showFilterModal && (
        <FilterModal
          setShowFilterModal={setShowFilterModal}
          showFilterModal={showFilterModal}
          setStateId={setStateId}
          setCityId={setCityId}
          setCategory={setCategory}
          setSort={setSort}
          stateId={stateId}
          cityId={cityId}
          category={category}
          sort={sort}
          handleFilterChange={handleFilterChange}
          clearFilters={clearFilters}
        />
      )}
    </div>
  );
}

export default BillboardsFilter;
