"use client";

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

// Data
import states from "@/data/state.json";
import cities from "@/data/city.json";
import Content from "./Content";

function ModalSearchCity({
  open,
  filter,
  sendReq,
  setOpen,
  children,
  setFilter,
  setDataInURL,
}) {
  const stateSelected = filter?.state?.name;

  const [filteredCities, setFilteredCities] = useState([]);

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

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

  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
            states={states}
            filter={filter}
            sendReq={sendReq}
            setFilter={setFilter}
            handleClose={handleClose}
            setDataInURL={setDataInURL}
            filteredCities={filteredCities}
          />
        </Box>
      </Modal>
    </>
  );
}

export default ModalSearchCity;
