import { useState } from "react";
import { ButtonGroup } from "@mui/material";
import AutoSearch from "./AutoSearch";
import { useRouter } from "next/navigation";
import FilterButton from "./FilterButton";
import ButtonFilter from "./filter/ButtonFilter";
import ModalSearchCity from "./filter";

// Req
import { QueryForClinicsFilter } from "@/helper";
import { request } from "@/services/response";

function SearchBar({
  state,
  limit,
  setPage,
  selected,
  specialties,
  setSelected,
  setFilteredClinics,
}) {
  const [open, setOpen] = useState(false);
  const router = useRouter();

  const handleSearch = (e) => {
    const specialty = specialties.find((item) => item.name === e);
    const searchParams = new URLSearchParams(window.location.search);

    if (specialty) {
      searchParams.set("specialty", specialty.name);
      setSelected({ ...selected, specialty: specialty.name });
    } else {
      e ? searchParams.set("specialty", e) : searchParams.delete("specialty");
      setSelected({ ...selected, specialty: e });
    }
    router.push(`?${searchParams.toString()}`);
  };

  const filterData = (newSelected) => {
    const data = newSelected || selected;
    const params = QueryForClinicsFilter(data);

    return request
      .getClinicList(params)
      .then((res) => {
        if (res.data) setFilteredClinics(res.data);
        return res;
      })
      .catch((err) => {
        throw err;
      });
  };

  return (
    <ButtonGroup
      variant="contained"
      className=" !bg-[#FFF] !w-full sm:!w-2/3 !mt-[30px] !rounded-lg !overflow-hidden flex items-center !shadow-[0px_1px_24.8px_0px_rgba(204,_204,_204,_0.18)] !h-fit !pl-1"
    >
      <ModalSearchCity
        open={open}
        limit={limit}
        state={state}
        setOpen={setOpen}
        setPage={setPage}
        selected={selected}
        filterData={filterData}
        setSelected={setSelected}
      >
        <ButtonFilter setOpen={setOpen} selected={selected} />
      </ModalSearchCity>
      <AutoSearch
        data={specialties}
        placeholder="جستجوی تخصص"
        handleSearch={handleSearch}
        inputValue={selected.specialty}
      />
      <FilterButton limit={limit} selected={selected} filterData={filterData} />
    </ButtonGroup>
  );
}

export default SearchBar;
