"use client";

import { useMemo } 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 handleClose = () => setOpen(false);

  const filteredCities = useMemo(() => {
    if (!stateSelected) return [];
    const selectedState = states.find((s) => s.name === stateSelected);
    if (!selectedState) return [];
    return cities.filter((c) => c.province_id === selectedState.id);
  }, [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;
