"use client";

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

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

function ModalSearchCity({
  open,
  state,
  setOpen,
  children,
  selected,
  handleSearch,
  setSelected,
}) {
  const provinceSelected = selected.province;

  const states = addLabelToList(statesData);
  const cities = addLabelToList(citiesData);
  const [filteredCities, setFilteredCities] = useState([]);

  const handleClose = () => setOpen(false);

  useEffect(() => {
    if (provinceSelected) {
      const selectedState = states.find(
        (state) => state.label === provinceSelected
      );
      if (selectedState) {
        const stateId = selectedState.id;
        const filteredCities = cities.filter(
          (city) => city.province_id === stateId
        );
        setFilteredCities(filteredCities);
      }
    } else {
      setFilteredCities([]);
    }
  }, [provinceSelected]);

  const updateData = (event, name) => {
    if (name === "province") {
      setSelected({ ...selected, province: event, city: "" });
    } else {
      setSelected({ ...selected, [name]: event });
    }
  };

  return (
    <>
      {/* Button Modal */}
      {children}

      {/* Content Modal */}
      <Modal open={open} onClose={handleClose}>
        <Box sx={styleDefault} className="!w-full !h-full md:!w-fit md:!h-fit">
          <Content
            state={state}
            states={states}
            selected={selected}
            updateData={updateData}
            handleClose={handleClose}
            handleSearch={handleSearch}
            filteredCities={filteredCities}
          />
        </Box>
      </Modal>
    </>
  );
}

export default ModalSearchCity;
