"use client";
import { useRouter, usePathname } from "next/navigation";
import React, { useEffect, useState } from "react";
import toast from "react-hot-toast";
import BoldIcon from "@/components/ui/BoldIcon";
import FilterModal from "./FilterModal";
import { getCreatePostPath } from "@/lib/getCreateContentPath";
import provinces from "@/data/provinces.json";
import cities from "@/data/cities.json";
import {
  appendAppearanceFiltersToSearch,
  readAppearanceFiltersFromSearch,
} from "@/lib/appearanceOptions";
import { isModelExpertise } from "@/lib/isModelExpertise";
import { readLocalStorage } from "@/lib/safeStorage";
import { useTranslation } from "react-i18next";
import { validateMinMaxPairs } from "@/lib/rangeValidation";

const TOOLBAR_ICON_SIZE = 25;
const toolbarIconButtonClass =
  "inline-flex h-[25px] w-[25px] items-center justify-center shrink-0 p-0 leading-none";

interface ModelsFilterProps {
  expertise: string;
}

function ModelsFilter({ expertise }: ModelsFilterProps) {
  const { t } = useTranslation("common");
  const router = useRouter();
  const pathname = usePathname();
  const [showFilterModal, setShowFilterModal] = useState<boolean>(false);
  const [stateId, setStateId] = useState<string>("");
  const [cityId, setCityId] = useState<string>("");
  const [rateFilter, setRateFilter] = useState<string>("");
  const [userLevel, setUserLevel] = useState<string>("");
  const [selectedExpertise, setSelectedExpertise] = useState<string>(expertise);
  const [heightMin, setHeightMin] = useState("");
  const [heightMax, setHeightMax] = useState("");
  const [weightMin, setWeightMin] = useState("");
  const [weightMax, setWeightMax] = useState("");
  const [sizeMin, setSizeMin] = useState("");
  const [sizeMax, setSizeMax] = useState("");
  const [hairColor, setHairColor] = useState("");
  const [eyeColor, setEyeColor] = useState("");
  const [userType, setUserType] = useState<string | null>(null);

  useEffect(() => {
    setSelectedExpertise(expertise);
  }, [expertise]);

  useEffect(() => {
    if (typeof window !== "undefined") {
      setUserType(readLocalStorage("usertype"));
    }
  }, []);

  useEffect(() => {
    if (typeof window === "undefined") return;
    const params = new URLSearchParams(window.location.search);
    const appearance = readAppearanceFiltersFromSearch(params);
    setHeightMin(appearance.heightMin || "");
    setHeightMax(appearance.heightMax || "");
    setWeightMin(appearance.weightMin || "");
    setWeightMax(appearance.weightMax || "");
    setSizeMin(appearance.sizeMin || "");
    setSizeMax(appearance.sizeMax || "");
    setHairColor(appearance.hair_color || "");
    setEyeColor(appearance.eye_color || "");
    setRateFilter(params.get("rateFilter") || "");
  }, [pathname]);

  const handleCreatePost = () => {
    if (!userType) {
      toast.error(t("filters.loginRequired"));
      return;
    }
    router.push(getCreatePostPath());
  };

  const handleFilterChange = () => {
    if (
      validateMinMaxPairs([
        { min: heightMin, max: heightMax },
        { min: weightMin, max: weightMax },
        { min: sizeMin, max: sizeMax },
      ])
    ) {
      toast.error(t("filters.maxMustBeGreater"));
      return;
    }

    const currentExpertise = selectedExpertise || "";
    const currentLevel = userLevel;

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

    const isVideoPage = pathname.startsWith("/videos");
    const basePath = isVideoPage ? "/videos" : "";
    const prefix = isVideoPage ? "ویدئو-ها-و-نمونه-کارهای" : "استخدام";

    const slugParts = [];

    if (currentExpertise) {
      slugParts.push(`${prefix}-${currentExpertise.replace(/\s+/g, "-")}`);
    } else {
      slugParts.push(
        isVideoPage
          ? "ویدئو-ها-متخصصین-مد-و-زیبایی"
          : "استخدام-متخصصین-مد-و-زیبایی"
      );
    }

    if (currentLevel) {
      slugParts.push(`سطح-${currentLevel.replace(/\s+/g, "-")}`);
    }

    if (cityObj) {
      slugParts.push(`در-شهر-${cityObj.name.replace(/\s+/g, "-")}`);
    } else if (provinceObj) {
      slugParts.push(`در-استان-${provinceObj.name.replace(/\s+/g, "-")}`);
    }

    const finalSlug = slugParts.join("-");
    const query = new URLSearchParams();

    if (rateFilter) query.set("rateFilter", rateFilter);
    if (isModelExpertise(currentExpertise)) {
      appendAppearanceFiltersToSearch(query, {
        heightMin,
        heightMax,
        weightMin,
        weightMax,
        sizeMin,
        sizeMax,
        hair_color: hairColor,
        eye_color: eyeColor,
      });
    }

    const qs = query.toString();
    router.push(
      `${basePath}/${encodeURIComponent(finalSlug)}${qs ? `?${qs}` : ""}`
    );
  };

  const clearFilters = () => {
    setStateId("");
    setCityId("");
    setRateFilter("");
    setUserLevel("");
    setSelectedExpertise("");
    setHeightMin("");
    setHeightMax("");
    setWeightMin("");
    setWeightMax("");
    setSizeMin("");
    setSizeMax("");
    setHairColor("");
    setEyeColor("");

    const basePath = pathname.startsWith("/videos") ? "/videos" : "/";
    router.push(basePath);
    setShowFilterModal(false);
  };

  return (
    <div>
      <div className="flex items-center justify-end gap-3 py-1 text-sm">
        <button
          type="button"
          onClick={handleCreatePost}
          aria-label={t("filters.toolbar.newPost")}
          className={toolbarIconButtonClass}
        >
          <BoldIcon name="add-square" size={TOOLBAR_ICON_SIZE} className="block" />
        </button>
        <button
          type="button"
          onClick={() => router.push("/search?type=user")}
          aria-label={t("filters.toolbar.searchUser")}
          className={toolbarIconButtonClass}
        >
          <BoldIcon name="search-normal" size={TOOLBAR_ICON_SIZE} className="block" />
        </button>
        <button
          type="button"
          onClick={() => setShowFilterModal(true)}
          aria-label={t("filters.toolbar.filter")}
          className={toolbarIconButtonClass}
        >
          <BoldIcon name="candle" size={TOOLBAR_ICON_SIZE} className="block" />
        </button>
        <button
          type="button"
          onClick={() => router.push("/explore")}
          aria-label={t("filters.toolbar.explore")}
          className={toolbarIconButtonClass}
        >
          <BoldIcon name="grid-3" size={TOOLBAR_ICON_SIZE} className="block" />
        </button>
        <button
          type="button"
          onClick={() => router.push("/shops/discover")}
          aria-label={t("filters.toolbar.shop")}
          className={toolbarIconButtonClass}
        >
          <BoldIcon name="shop" size={TOOLBAR_ICON_SIZE} className="block" />
        </button>
      </div>
      {showFilterModal && (
        <FilterModal
          setShowFilterModal={setShowFilterModal}
          showFilterModal={showFilterModal}
          setStateId={setStateId}
          setCityId={setCityId}
          setRateFilter={setRateFilter}
          setUserLevel={setUserLevel}
          selectedExpertise={selectedExpertise}
          setSelectedExpertise={setSelectedExpertise}
          heightMin={heightMin}
          setHeightMin={setHeightMin}
          heightMax={heightMax}
          setHeightMax={setHeightMax}
          weightMin={weightMin}
          setWeightMin={setWeightMin}
          weightMax={weightMax}
          setWeightMax={setWeightMax}
          sizeMin={sizeMin}
          setSizeMin={setSizeMin}
          sizeMax={sizeMax}
          setSizeMax={setSizeMax}
          hairColor={hairColor}
          setHairColor={setHairColor}
          eyeColor={eyeColor}
          setEyeColor={setEyeColor}
          stateId={stateId}
          cityId={cityId}
          rateFilter={rateFilter}
          userLevel={userLevel}
          handleFilterChange={handleFilterChange}
          clearFilters={clearFilters}
        />
      )}
    </div>
  );
}

export default ModelsFilter;
