"use client ";

import SearchBar from "./search";
import SortList from "./sortlist";
import { useRouter, useSearchParams } from "next/navigation";
import specialties from "@/data/specialties.json";
import { QueryForClinicDoctorFilter, QueryForDoctorsClinicReq } from "@/helper";
import { getClinicDoctors } from "@/services/clinicApi";


function Head({ setDoctors, slug, filter, setFilter,setPage,setTotalPage }) {
  const searchParams = useSearchParams();
 
  const router = useRouter();

  const fieldName = searchParams.get("specialty");

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

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

  const findItem = (key, name) =>
    specialties.find((item) => item[key] === name);
  const isParent =
    findItem("name", fieldName) && findItem("name", fieldName).parent;

  const valCategory = isParent
    ? findItem("id", isParent)
    : findItem("name", fieldName);
  const valSpecialty = isParent && findItem("name", fieldName);

  const defaultFilter = {
    category: valCategory,
    specialty: valSpecialty,
    active: searchParams.get("active") || 0,
    gender: searchParams.get("gender") || "هر دو",
    degree: searchParams.get("degree") || "همه موارد",
    sort: (searchParams.get("sort") && Number(searchParams.get("sort"))) || "",
    name:
      searchParams.get("name") || valSpecialty?.name || valCategory?.name || "",
  };


  const updateData = (name, value) => {
    const newFilter = { ...filter, [name]: value };
    setDataInURL(newFilter);
    setFilter(newFilter);
    sendReq(newFilter);
  };

  const sendReq = async (newFilter) => {
    try {
    const data = newFilter || filter;
    let params = QueryForDoctorsClinicReq(data);

    
     if (
      data?.specialty &&
      (data?.name === data.specialty?.name ||
        data?.name === data.category?.name)
    ) {
      delete params.name;
    }

    params.page = 1;
    params.limit = 50;

    // دریافت دکترها از API
    const doctors = await getClinicDoctors(slug, params);

    // تنظیم داده‌ها در state
    setDoctors(doctors.data);

    // ✅ حالا که جواب API اومده، مقدار صفحات مشخصه
    if (doctors?.page) {
      setPage(doctors.page.current || 1);
      setTotalPage(doctors.page.total_pages || 1);
    } else {
      setPage(1);
      setTotalPage(1);
    }

    return doctors;
  } catch (err) {
    console.error("❌ خطا در sendReq:", err);
    throw err;
  }
    
  };

  return (
    <div className="flex flex-col lg:flex-row items-start lg:items-center justify-center gap-[24px] lg:gap-[32px] w-full">
      <SearchBar
        slug={slug}
        filter={filter}
        sendReq={sendReq}
        setFilter={setFilter}
        updateData={updateData}
        setDataInURL={setDataInURL}
        setPage={setPage}
        setTotalPage={setTotalPage}
      />
      <SortList
        filter={filter}
        sendReq={sendReq}
        setFilter={setFilter}
        updateData={updateData}
        setDataInURL={setDataInURL}
      />
    </div>
  );
}

export default Head;
