import ItemDoctor from "@/app/component/ItemDoctor";
import Pagination from "@/app/component/Pagination";
import { QueryForDoctorsClinicReq } from "@/helper";
import { getClinicDoctors } from "@/services/clinicApi";
import { useRouter } from "next/navigation";
import { useState } from "react";

function List({
  doctors,
  setPage,
  limit,
  page,
  filter,
  setDoctors,
  totalPages,
  slug,
  setTotalPage,
}) {
  const [loading, setLoading] = useState(false);
  const router = useRouter();
  const changePage = async (_, num) => {
    setLoading(true);

    window.scrollTo({ top: 0, behavior: "smooth" });

    const searchParams = new URLSearchParams(window.location.search);
    searchParams.set("page", num);
    router.push(`/clinic/${slug}?${searchParams.toString()}`);

    setPage(num);
    try {
      let params = {
        ...QueryForDoctorsClinicReq(filter),
        page: num,
        limit,
      };

      const res = await getClinicDoctors(slug, params);

      // اگر سرور داده را در data برمی‌گرداند
      if (res?.data) {
        setDoctors([...res.data]);
        setTotalPage(res?.page?.total_pages || 1);
      }
      // اگر فقط آرایه برمی‌گرداند
      else if (Array.isArray(res)) {
        setDoctors([...res]);
        setTotalPage(1);
      }

      setPage(num);
    } catch (error) {
      console.error("❌ خطا در دریافت داده:", error);
    } finally {
      setLoading(false);
    }
  };
  const doctorList = Array.isArray(doctors)
    ? doctors
    : Array.isArray(doctors?.data)
      ? doctors.data
      : [];
  return (
    <>
      { doctorList?.length === 0 ? (
        <div className="text-center text-gray-500 mt-10">
          دکتری مطابق فیلتر شما یافت نشد
        </div>
      ) : (
        <>
          <ul className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 mt-[40px] gap-[16px] md:gap-[20px] lg:gap-[24px]">
            {doctorList?.map((doctor) => (
              <ItemDoctor
                loading={loading}
                setDoctors={setDoctors}
                key={doctor.id}
                doctor={doctor}
              />
            ))}
          </ul>
          <div className="mt-[56px] flex justify-center">
            <Pagination
              totalPages={totalPages}
              page={page}
              onPageChange={changePage}
            />
          </div>
        </>
      )}
    </>
  );
}

export default List;
