"use client";

import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import Modal from "../elements/Modal";
import { ICity, IExpertise, IProvince } from "@/types/types";
import useAxios from "@/hooks/useAxios";
import SelectBox from "../elements/SelectBox";
import RoundedInput from "../elements/RoundedInput";
import {
  EYE_COLOR_OPTIONS,
  HAIR_COLOR_OPTIONS,
} from "@/lib/appearanceOptions";
import AppearanceColorSelect from "./AppearanceColorSelect";
import { isModelExpertise } from "@/lib/isModelExpertise";
import RoundedButton from "../elements/RoundedButton";
import { filterChipClass } from "@/lib/ui/buttonStyles";

interface IFilterProps {
  setShowFilterModal: (e: boolean) => void;
  setStateId: (e: string) => void;
  setCityId: (e: string) => void;
  setRateFilter: (e: string) => void;
  setUserLevel: (e: string) => void;
  selectedExpertise: string;
  setSelectedExpertise: (value: string) => void;
  heightMin: string;
  setHeightMin: (value: string) => void;
  heightMax: string;
  setHeightMax: (value: string) => void;
  weightMin: string;
  setWeightMin: (value: string) => void;
  weightMax: string;
  setWeightMax: (value: string) => void;
  sizeMin: string;
  setSizeMin: (value: string) => void;
  sizeMax: string;
  setSizeMax: (value: string) => void;
  hairColor: string;
  setHairColor: (value: string) => void;
  eyeColor: string;
  setEyeColor: (value: string) => void;
  handleFilterChange: () => void;
  showFilterModal: boolean;
  stateId: string;
  cityId: string;
  rateFilter: string;
  userLevel: string;
  clearFilters: () => void;
}

const LEVEL_OPTIONS = [
  { key: "newcomer", id: "تازه وارد" },
  { key: "standard", id: "استاندارد" },
  { key: "professional", id: "حرفه‌ای" },
  { key: "supermodel", id: "سپورمدل" },
  { key: "master", id: "استاد" },
] as const;

function RangeField({
  label,
  min,
  max,
  onMinChange,
  onMaxChange,
  minPlaceholder,
  maxPlaceholder,
}: {
  label: string;
  min: string;
  max: string;
  onMinChange: (v: string) => void;
  onMaxChange: (v: string) => void;
  minPlaceholder: string;
  maxPlaceholder: string;
}) {
  return (
    <div className="w-full max-w-sm">
      <p className="mb-1.5 text-center text-xs text-neutral-500">{label}</p>
      <div className="flex gap-2">
        <RoundedInput
          type="number"
          inputMode="numeric"
          placeholder={minPlaceholder}
          value={min}
          onChange={(e) => onMinChange(e.target.value)}
          className="text-center text-sm"
        />
        <RoundedInput
          type="number"
          inputMode="numeric"
          placeholder={maxPlaceholder}
          value={max}
          onChange={(e) => onMaxChange(e.target.value)}
          className="text-center text-sm"
        />
      </div>
    </div>
  );
}

function FilterModal({
  setStateId,
  setCityId,
  setRateFilter,
  setUserLevel,
  selectedExpertise,
  setSelectedExpertise,
  heightMin,
  setHeightMin,
  heightMax,
  setHeightMax,
  weightMin,
  setWeightMin,
  weightMax,
  setWeightMax,
  sizeMin,
  setSizeMin,
  sizeMax,
  setSizeMax,
  hairColor,
  setHairColor,
  eyeColor,
  setEyeColor,
  stateId,
  cityId,
  rateFilter,
  userLevel,
  setShowFilterModal,
  showFilterModal,
  handleFilterChange,
  clearFilters,
}: IFilterProps) {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const [allStates, setAllStates] = useState<IProvince[] | null>(null);
  const [cities, setCities] = useState<ICity[] | null>(null);
  const [expertiseList, setExpertiseList] = useState<IExpertise[]>([]);
  const [loadingExpertise, setLoadingExpertise] = useState(false);

  useEffect(() => {
    const fetchStates = async () => {
      const response = await request<{ provinces: IProvince[] }>(
        "GET",
        "/provinces"
      );
      setAllStates(response?.provinces || null);
    };
    fetchStates();
  }, []);

  useEffect(() => {
    if (!showFilterModal) return;

    const fetchExpertise = async () => {
      setLoadingExpertise(true);
      try {
        const response = await request<{ expertises: IExpertise[] }>(
          "GET",
          "/expertise"
        );
        setExpertiseList(response?.expertises ?? []);
      } catch {
        setExpertiseList([]);
      } finally {
        setLoadingExpertise(false);
      }
    };

    void fetchExpertise();
  }, [showFilterModal]);

  useEffect(() => {
    if (stateId) {
      const fetchCities = async () => {
        const response = await request<{ cities: ICity[] }>(
          "GET",
          `/cities/${stateId}`
        );
        setCities(response?.cities || []);
      };
      fetchCities();
    }
  }, [stateId]);

  const clearAppearanceFilters = () => {
    setHeightMin("");
    setHeightMax("");
    setWeightMin("");
    setWeightMax("");
    setSizeMin("");
    setSizeMax("");
    setHairColor("");
    setEyeColor("");
  };

  const handleExpertiseSelect = (expertise: string) => {
    setSelectedExpertise(expertise);
    if (!isModelExpertise(expertise)) {
      clearAppearanceFilters();
    }
  };

  const showAppearanceFilters = isModelExpertise(selectedExpertise);

  return (
    <Modal
      isOpen={showFilterModal}
      onClose={() => setShowFilterModal(false)}
      height="fit"
      elevated
      panelClassName="!p-0 max-h-[90dvh] w-full overflow-y-auto overscroll-y-contain touch-pan-y [-webkit-overflow-scrolling:touch]"
    >
      <div className="px-4 pt-5 pb-[calc(6rem+env(safe-area-inset-bottom,0px))]">
        <div className="mx-auto flex w-full max-w-sm flex-col items-center">
          <span className="mb-4 block text-center font-semibold">
            {t("filters.title")}
          </span>

        <div className="mb-4 w-full">
          <p className="mb-2 text-center text-xs text-neutral-500">
            {t("filters.expertise")}
          </p>
          {loadingExpertise ? (
            <p className="py-2 text-center text-xs text-neutral-400">
              {t("filters.loadingExpertise")}
            </p>
          ) : (
            <div className="flex flex-wrap justify-center gap-2">
              <button
                type="button"
                className={filterChipClass(!selectedExpertise)}
                onClick={() => handleExpertiseSelect("")}
              >
                {t("filters.all")}
              </button>
              {expertiseList.map((item) => {
                const isActive = selectedExpertise === item.expertise;
                return (
                  <button
                    key={item._id}
                    type="button"
                    className={filterChipClass(isActive)}
                    onClick={() =>
                      handleExpertiseSelect(isActive ? "" : item.expertise)
                    }
                  >
                    {item.expertise}
                  </button>
                );
              })}
            </div>
          )}
        </div>

        {showAppearanceFilters && (
        <div className="mb-4 w-full space-y-4 border-t border-neutral-200 pt-4 dark:border-neutral-700">
          <p className="text-center text-xs font-semibold text-neutral-600 dark:text-neutral-300">
            {t("filters.appearanceModel")}
          </p>

          <RangeField
            label={t("filters.heightCm")}
            min={heightMin}
            max={heightMax}
            onMinChange={setHeightMin}
            onMaxChange={setHeightMax}
            minPlaceholder={t("filters.min")}
            maxPlaceholder={t("filters.max")}
          />

          <RangeField
            label={t("filters.weightKg")}
            min={weightMin}
            max={weightMax}
            onMinChange={setWeightMin}
            onMaxChange={setWeightMax}
            minPlaceholder={t("filters.min")}
            maxPlaceholder={t("filters.max")}
          />

          <RangeField
            label={t("filters.size")}
            min={sizeMin}
            max={sizeMax}
            onMinChange={setSizeMin}
            onMaxChange={setSizeMax}
            minPlaceholder={t("filters.min")}
            maxPlaceholder={t("filters.max")}
          />

          <AppearanceColorSelect
            label={t("filters.hairColor")}
            placeholder={t("filters.selectHairColor")}
            value={hairColor}
            options={HAIR_COLOR_OPTIONS}
            onChange={setHairColor}
          />

          <AppearanceColorSelect
            label={t("filters.eyeColor")}
            placeholder={t("filters.selectEyeColor")}
            value={eyeColor}
            options={EYE_COLOR_OPTIONS}
            onChange={setEyeColor}
          />
        </div>
        )}

        <SelectBox
          className="mt-2 w-full"
          value={stateId}
          onChange={(e) => setStateId(e.target.value)}
        >
          <option disabled value="">
            {t("filters.province")}
          </option>
          {allStates?.map((item) => (
            <option key={item.id} value={item.id}>
              {item.name}
            </option>
          ))}
        </SelectBox>
        <SelectBox
          className="mt-4 w-full"
          value={cityId}
          onChange={(e) => setCityId(e.target.value)}
        >
          <option disabled value="">
            {t("filters.city")}
          </option>
          {cities?.map((city) => (
            <option key={city.id} value={city.id}>
              {city.name}
            </option>
          ))}
        </SelectBox>
        <SelectBox
          className="mt-4 w-full"
          value={userLevel}
          onChange={(e) => setUserLevel(e.target.value)}
        >
          <option disabled value="">
            {t("filters.userLevel")}
          </option>
          {LEVEL_OPTIONS.map((item) => (
            <option key={item.id} value={item.id}>
              {t(`filters.levels.${item.key}`)}
            </option>
          ))}
        </SelectBox>
        <SelectBox
          className="mt-4 w-full"
          value={rateFilter}
          onChange={(e) => setRateFilter(e.target.value)}
        >
          <option disabled value="">
            {t("filters.sortByRating")}
          </option>
          <option value="بیشترین">{t("filters.highestRating")}</option>
          <option value="کمترین">{t("filters.lowestRating")}</option>
        </SelectBox>

          <div className="mt-6 flex w-full flex-col items-center gap-3 border-t border-neutral-200 pt-5 dark:border-neutral-700">
        <RoundedButton
          type="button"
          variant="primary"
          onClick={() => {
            handleFilterChange();
            setShowFilterModal(false);
          }}
          className="h-10 w-full max-w-[200px] text-sm"
        >
          {t("filters.apply")}
        </RoundedButton>
        <RoundedButton
          type="button"
          onClick={() => clearFilters()}
          className="h-10 w-full max-w-[200px] text-sm"
        >
          {t("filters.clear")}
        </RoundedButton>
          </div>
        </div>
      </div>
    </Modal>
  );
}

export default FilterModal;
