import SearchBar from "../search";
import SortList from "../sortlist";
import { useRouter } from "next/navigation";

// Data
import { QueryForDoctorsFilter, QueryForDoctorsReq } from "@/helper";
import { request } from "@/services/response";
import FilterLocate from "./FilterLocate";

function Head({ filter, setFilter, setPage, setDoctors, setLoading }) {
  const router = useRouter();

  const setDataInURL = (newFilter) => {
    const query = QueryForDoctorsFilter(newFilter);

    const searchParams = new URLSearchParams(query).toString();
    router.push(`?${searchParams}`);
  };

  const updateData = (name, value, isReq) => {
    const newFilter = { ...filter, [name]: value };
    setDataInURL(newFilter);
    setFilter(newFilter);
    isReq && sendReq(newFilter);
  };
  const sendReq = (newFilter) => {
    const data = newFilter || filter;
    const params = QueryForDoctorsReq(data);
    let filteredName = params;
    if (
      data?.name === data.specialty?.name ||
      data?.name === data.category?.name
    ) {
      filteredName.name = "";
      delete filteredName.name;
    }

    filteredName.page = 1;
    filteredName.limit = 12;
    setPage(1);
    setLoading(true);

    return request
      .getDoctors(filteredName)
      .then((res) => {
        setDoctors(res.data);
        return res;
      })
      .catch((err) => {
        throw err;
      })
      .finally(() => {
        setLoading(false);
      });
  };

  return (
    <div className="flex justify-center gap-[16px] sm:gap-[19px] md:gap-[22px] lg:gap-[24px] flex-col items-center mt-0 md:mt-[40px] lg:mt-[90px]">
      <FilterLocate
        filter={filter}
        setPage={setPage}
        sendReq={sendReq}
        setFilter={setFilter}
        setDataInURL={setDataInURL}
      />
      <div className="flex flex-col lg:flex-row items-start lg:items-center justify-center gap-[24px] lg:gap-[32px] w-full">
        <SearchBar
          filter={filter}
          sendReq={sendReq}
          setFilter={setFilter}
          updateData={updateData}
          setDataInURL={setDataInURL}
        />
        <SortList
          filter={filter}
          sendReq={sendReq}
          setFilter={setFilter}
          updateData={updateData}
          setDataInURL={setDataInURL}
        />
      </div>
    </div>
  );
}

export default Head;
