"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";
import { useRouter } from "next/navigation";

function ModalSearchCity({
  open,
  state,
  limit,
  setPage,
  setOpen,
  children,
  selected,
  filterData,
  setSelected,
  handleSearch,
}) {
  const provinceSelected = selected?.province?.name;
  const router = useRouter();
  const [filteredCities, setFilteredCities] = useState([]);

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

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

  const updateData = (name, event) => {
    const searchParams = new URLSearchParams(window.location.search);

    if (name === "province") {
      setSelected({ ...selected, province: event, city: "" });
      searchParams.set("state", event?.name);
      searchParams.delete("city");
      searchParams.delete("page");
      setPage(1);
    } else {
      setSelected({ ...selected, [name]: event });
      searchParams.set("city", event?.name);
      searchParams.set("state", selected.province?.name);
    }
    router.push(`?${searchParams.toString()}`);
  };

  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
            limit={limit}
            state={state}
            states={states}
            selected={selected}
            updateData={updateData}
            filterData={filterData}
            handleClose={handleClose}
            handleSearch={handleSearch}
            filteredCities={filteredCities}
          />
        </Box>
      </Modal>
    </>
  );
}

export default ModalSearchCity;
