"use client";

import { useState, useEffect } from "react";
import { Box, Button, Modal } from "@mui/material";

// Icon
import ArrowBottomH from "@/components/icons/ArrowBottomH";
import Location from "@/components/icons/Location";
import { styleDefault } from "@/mui";
import CloseModalD from "@/components/icons/CloseModalD";
import AutoCompleteSelect from "@/app/component/element/AutoCompleteSelect";
import ArrowLeftM from "@/components/icons/ArrowLeftM";

// Data
import statesData from "@/data/state.json";
import citiesData from "@/data/city.json";

function ModalSearchCity() {
  const [states, setStates] = useState([]);
  const [cities, setCities] = useState([]);
  const [filteredCities, setFilteredCities] = useState([]);

  const [open, setOpen] = useState(false);
  const handleOpen = () => setOpen(true);
  const handleClose = () => setOpen(false);

  const [selected, setSelected] = useState({
    first: "",
    second: "",
  });

  // Load states and cities from JSON files
  useEffect(() => {
    // Format states data to match the structure expected by AutoCompleteSelect
    const formattedStates = statesData.map((state) => ({
      label: state.name,
      id: state.id,
    }));

    // Format cities data
    const formattedCities = citiesData.map((city) => ({
      label: city.name,
      id: city.id,
      province_id: city.province_id,
    }));

    setStates(formattedStates);
    setCities(formattedCities);
  }, []);

  // Filter cities when state is selected
  useEffect(() => {
    if (selected.first) {
      const selectedState = states.find(
        (state) => state.label === selected.first,
      );
      if (selectedState) {
        const stateId = selectedState.id;
        const filteredCities = cities.filter(
          (city) => city.province_id === stateId,
        );
        setFilteredCities(filteredCities);
      }
    } else {
      setFilteredCities([]);
      setSelected({ ...selected, second: "" });
    }
  }, [selected.first, cities, states]);

  const updateData = (event, name) => {
    if (name === "first" && event !== selected.first) {
      // If state changes, reset city selection
      setSelected({ first: event, second: "" });
    } else {
      setSelected({ ...selected, [name]: event });
    }
  };

  return (
    <>
      {/* Button Modal */}
      <Button
        className="!border-none hover:!bg-transparent !py-[11.5px] !min-w-fit !px-[7px] sm:!py-3 sm:!px-[9px] md:!px-[11px] lg:!px-[12px] !rounded-3"
        onClick={handleOpen}
        variant="contained"
        color="secondary"
      >
        <div className="min-w-[20px] min-h-[20px] hidden md:flex">
          <Location />
        </div>
        <p
          className={`text-[#616161] text-[11px] md:text-[14px] leading-[17px] sm:leading-[19px] 
          md:leading-[22px] lg:leading-[24px] font-medium ml-1 md:mx-1
          ${selected.first && selected.second ? "" : ""}`}
        >
          {selected.first && selected.second
            ? `${selected.first} | ${selected.second}`
            : "انتخاب شهر"}
        </p>
        <div className="w-[16px] h-[16px] md:w-[18px] md:h-[18px] lg:w-[20px] lg:h-[20px] grid place-items-center">
          <ArrowBottomH />
        </div>
      </Button>
      {/* Content Modal */}
      <Modal open={open} onClose={handleClose}>
        <Box sx={styleDefault} className="!w-full !h-full md:!w-fit md:!h-fit">
          <div className="flex justify-end w-full">
            <div className="cursor-pointer" onClick={handleClose}>
              <CloseModalD />
            </div>
          </div>
          <div className="md:p-[24px] pt-0">
            <p className="text-[#525252] mt-[38px] md:mt-4 text-[16px] font-medium text-center">
              شهر یا استان مورد نظر را انتخاب نمایید:
            </p>
            <div className="flex md:min-w-[344px] flex-col mt-[52px] md:mt-[44px] mb-14 justify-center items-center gap-10">
              <AutoCompleteSelect
                updateData={updateData}
                list={states}
                label="استان"
                name="first"
              />
              <AutoCompleteSelect
                updateData={updateData}
                list={filteredCities}
                name="second"
                label="شهر"
                disabled={!selected.first || filteredCities.length === 0}
              />
            </div>
            <div className="w-full flex justify-end">
              <Button
                className="!w-full md:!w-fit !flex !px-3 items-center justify-center gap-1 mr-auto"
                onClick={handleClose}
                variant="contained"
                color="primary"
                disabled={!selected.first || !selected.second}
              >
                تایید و ادامه
                <ArrowLeftM />
              </Button>
            </div>
          </div>
        </Box>
      </Modal>
    </>
  );
}

export default ModalSearchCity;
