import React, { useState, useEffect } from "react";
import { Input } from "@/components/ui/input";
import {
  Building2,
  DoorOpen,
  Funnel,
  Globe,
  PersonStanding,
  Search,
  User,
  UserRoundSearch,
} from "lucide-react";
import CustomSelect from "../ui/select";
import Overlay from "../overlay/overlay";
import { useDispatch, useSelector } from "react-redux";
import {
  updateFilterValue,
  resetFilterValues,
  updateSearch,
} from "@/src/redux/appActions";
import { RootState } from "@/src/redux/store";
import { FilterValues } from "@/src/utils/types/state_types";
import { useScreenSizeContext } from "@/src/utils/providers/screenSizesContext";
import { Option } from "@/src/utils/types";
import { useAppSelector } from "@/src/redux/hook";
import { useGetInputData } from "@/src/utils/hooks/useGetInputData";
import { useGetAllMatches } from "@/src/utils/hooks/useGetMatches";

export default function SearchUi() {
  const dispatch = useDispatch();
  const filterValues = useSelector(
    (state: RootState) => state.counter.filterValues
  );

  const searchValue = useSelector((state: RootState) => state.counter.search);
  const [showFilterModal, setShowFilterModal] = useState<boolean>(false);
  const { isDesktop } = useScreenSizeContext();

  const handleShowFiltrModal = () => {
    setShowFilterModal(!showFilterModal);
  };

  const handleModalClick = (e: React.MouseEvent) => {
    e.stopPropagation();
  };

  useEffect(() => {
    const handleOutsideClick = (e: MouseEvent) => {
      e.stopPropagation();
      const modal = document.getElementById("filter_modal");
      const filter_modal = document.getElementById("filter");
      if (
        modal &&
        !modal.contains(e.target as Node) &&
        filter_modal &&
        !filter_modal.contains(e.target as Node)
      ) {
        setShowFilterModal(false);
        console.log(filterValues);
      }
    };

    document.addEventListener("mousedown", handleOutsideClick);
    if (showFilterModal) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "auto";
    }

    return () => {
      document.removeEventListener("mousedown", handleOutsideClick);
      document.body.style.overflow = "auto";
    };
  }, [showFilterModal, dispatch]);

  const handleFilterChange = (field: keyof FilterValues, value: string) => {
    dispatch(updateFilterValue({ field, value }));
  };

  useEffect(() => {
    console.log(searchValue, "search");
  }, [searchValue]);

  const useInputOptions = (
    keys: string[]
  ): { key: string; options: Option[]; rawValue?: any }[] => {
    return keys.map((key) => {
      const { data } = useGetInputData(key);

      // if nationality → we handle it specially
      if (key === "nationality" && data?.payload?.value) {
        return {
          key,
          options: Object.keys(data.payload.value).map((countryName) => ({
            label: countryName,
            value: countryName.toLowerCase(),
          })),
          rawValue: data.payload.value, // pass raw country object
        };
      }

      if (key === "religion" && data?.payload?.value) {
        return {
          key,
          options: Object.keys(data.payload.value).map((religionName) => ({
            label: religionName,
            value: religionName.toLowerCase(),
            subcategories: data.payload.value[religionName].denominations.map(
              (denomination: any) => ({
                label: denomination,
                value: denomination.toLowerCase(),
              })
            ),
          })),
          rawValue: data.payload.value, // Pass full religion data
        };
      }

      // other keys → normal options
      const options: Option[] =
        data?.payload?.value?.map((item: string) => ({
          label: item,
          value: item.toLowerCase(),
        })) || [];

      return { key, options };
    });
  };

  const inputKeys: string[] = [
    "marital_status",
    "height_range",
    "weight_range",
    "ethnicity",
    "genotype",
    "religion",
    "hobbies",
    "nationality",
    "interests",
    "language_spoken",
    "relationship_type",
    "age_range",
  ];

  const inputOptions = useInputOptions(inputKeys);

  const maritalOptions: Option[] =
    inputOptions.find((o) => o.key === "marital_status")?.options || [];
  const heightOptions: Option[] =
    inputOptions.find((o) => o.key === "height_range")?.options || [];
  const weightOptions: Option[] =
    inputOptions.find((o) => o.key === "weight_range")?.options || [];
  const ethnicityOptions: Option[] =
    inputOptions.find((o) => o.key === "ethnicity")?.options || [];
  const genotypeOptions: Option[] =
    inputOptions.find((o) => o.key === "genotype")?.options || [];
  const hobbiesOptions: Option[] =
    inputOptions.find((o) => o.key === "hobbies")?.options || [];
  const interestsOptions: Option[] =
    inputOptions.find((o) => o.key === "interests")?.options || [];
  const countryOptions: Option[] =
    inputOptions.find((o) => o.key === "nationality")?.options || [];
  const languagesOptions: Option[] =
    inputOptions.find((o) => o.key === "language_spoken")?.options || [];
  const ageOptions: Option[] =
    inputOptions.find((o) => o.key === "age_range")?.options || [];
  const relationshipOptions: Option[] =
    inputOptions.find((o) => o.key === "relationship_type")?.options || [];
  const nationalityRaw =
    inputOptions.find((o) => o.key === "nationality")?.rawValue || {};
  const religionOptions: Option[] =
    inputOptions.find((o) => o.key === "religion")?.options || [];

  const selectedCountry = filterValues.nationality;

  const countryKey = Object.keys(nationalityRaw)?.find(
    (name) => name.toLowerCase() === selectedCountry.toLowerCase()
  );

  const stateOptions: Option[] = countryKey
    ? nationalityRaw[countryKey].states.map((stateName: string) => ({
        label: stateName,
        value: stateName.toLowerCase(),
      }))
    : [];

  return (
    <div
      className="flex gap-x-4 items-center"
      onMouseDown={(e) => e.stopPropagation()}
      onClick={(e) => e.stopPropagation()}
    >
      <div className="flex items-center w-60 mx-8 rounded-full">
        <Search className="-mx-8 !text-[10px]" color="#00000099" size={15} />
        <Input
          type="text"
          placeholder="Search"
          onChange={(e) => dispatch(updateSearch(e.target.value))}
          value={searchValue}
          className="px-10 focus:border-[#3E7BEA] !text-[10px] text-[#00000099] focus:outline focus:outline-[#3E7BEA] focus:ring-0 outline-none border-[#3E7BEA] rounded-full"
        />
      </div>

      {isDesktop && (
        <div
          className="flex items-center w-24 -mx-6 cursor-pointer rounded-full"
          onClick={handleShowFiltrModal}
          id="filter"
          role="button"
        >
          <Funnel className="-mx-8" color="#00000099" />
          <Input
            type="text"
            placeholder="Filter"
            className="pl-9 focus:border-none focus:outline-none border border-[#00000099] rounded-full !text-[12px] !font-medium"
            disabled
          />
        </div>
      )}

      {showFilterModal && (
        <>
          <Overlay func={handleShowFiltrModal} />
          <div
            id="filter_modal"
            className="fixed lg:top-[10%] md:top-[8%] top-[5%] 
             lg:left-1/2 left-1/2 
             transform -translate-x-1/2 
             flex flex-col lg:w-[1035px] md:w-[800px] w-full 
             z-50 px-8 shadow shadow-[#00000066] 
             rounded-md bg-white py-2 min-h-[300px]"
            onClick={handleModalClick}
          >
            <div className="w-full border-b border-b-[#00000066] py-4 px-4 mb-2 flex gap-x-2 items-center">
              <span>
                <Funnel />
              </span>
              <h1 className="font-semibold text-[14px]">Shoot filters</h1>
            </div>

            <div className="flex flex-wrap gap-x-3">
              <div
                className="lg:w-[22%] md:w-[30%] w-full flex flex-col my-2 mx-1"
                onMouseDown={(e) => e.stopPropagation()}
              >
                <CustomSelect
                  value={filterValues.relationship_type}
                  onChange={(value) =>
                    handleFilterChange("relationship_type", value)
                  }
                  options={relationshipOptions}
                  label="Relationship"
                  placeholder="select"
                  icon={<User />}
                  weight={500}
                />
              </div>

              <div
                className="lg:w-[22%] md:w-[30%] w-full flex flex-col gap-y-2 my-2 mx-1"
                onMouseDown={(e) => e.stopPropagation()}
              >
                <CustomSelect
                  value={filterValues.age_range}
                  onChange={(value) => handleFilterChange("age_range", value)}
                  options={ageOptions}
                  label="Age Range"
                  placeholder="select"
                  icon={<PersonStanding />}
                  weight={500}
                />
              </div>

              <div
                className="lg:w-[22%] md:w-[30%] w-full flex flex-col gap-y-2 my-2 mx-1"
                onMouseDown={(e) => e.stopPropagation()}
              >
                <CustomSelect
                  value={filterValues.nationality}
                  onChange={(value) => handleFilterChange("nationality", value)}
                  options={countryOptions}
                  label="Nationality"
                  placeholder="select"
                  icon={<Globe />}
                  weight={500}
                />
              </div>

              <div
                className="lg:w-[22%] md:w-[30%] w-full flex flex-col gap-y-2 my-2 mx-1"
                onMouseDown={(e) => e.stopPropagation()}
              >
                <CustomSelect
                  value={filterValues.state}
                  onChange={(value) => handleFilterChange("state", value)}
                  options={stateOptions}
                  label="State"
                  placeholder="select"
                  icon={<Building2 />}
                  weight={500}
                />
              </div>

              <div
                className="lg:w-[22%] md:w-[30%] w-full flex flex-col gap-y-2 my-2 mx-1"
                onMouseDown={(e) => e.stopPropagation()}
              >
                <CustomSelect
                  value={filterValues.ethnicity}
                  onChange={(value) => handleFilterChange("ethnicity", value)}
                  options={ethnicityOptions}
                  label="Ethnicity"
                  placeholder="select"
                  icon={<Building2 />}
                  weight={500}
                />
              </div>

              <div
                className="lg:w-[22%] md:w-[30%] w-full flex flex-col gap-y-2 my-2 mx-1"
                onMouseDown={(e) => e.stopPropagation()}
              >
                <CustomSelect
                  value={filterValues.height_range}
                  onChange={(value) =>
                    handleFilterChange("height_range", value)
                  }
                  options={heightOptions}
                  label="Height Range"
                  placeholder="select"
                  icon={<PersonStanding />}
                  weight={500}
                />
              </div>

              <div
                className="lg:w-[22%] md:w-[30%] w-full flex flex-col gap-y-2 my-2 mx-1"
                onMouseDown={(e) => e.stopPropagation()}
              >
                <CustomSelect
                  value={filterValues.weight_range}
                  onChange={(value) =>
                    handleFilterChange("weight_range", value)
                  }
                  options={weightOptions}
                  label="Weight Range"
                  placeholder="select"
                  icon={<UserRoundSearch />}
                  weight={500}
                />
              </div>

              <div
                className="lg:w-[22%] md:w-[30%] w-full flex flex-col gap-y-2 my-2 mx-1"
                onMouseDown={(e) => e.stopPropagation()}
              >
                <CustomSelect
                  value={filterValues.religion}
                  onChange={(value) => handleFilterChange("religion", value)}
                  options={religionOptions}
                  label="Religion"
                  placeholder="select"
                  icon={<DoorOpen />}
                  weight={500}
                />
              </div>
            </div>

            <div className="flex justify-end mt-4 px-4 gap-x-4 absolute right-0 bottom-5 text-[12px] font-medium">
              <button
                className="px-4 py-2 bg-[#D9D9D9] rounded-md"
                onClick={() => dispatch(resetFilterValues())}
              >
                Reset
              </button>
              <button
                className="px-4 py-2 bg-[#00A389] text-white rounded-md"
                onClick={handleShowFiltrModal}
              >
                Apply
              </button>
            </div>
          </div>
        </>
      )}
    </div>
  );
}
