import { useState } from "react";
import ItemDoctor from "@/app/component/ItemDoctor";
import PaginationContent from "@/app/component/PaginationContent";
import { QueryForDoctorsReq } from "@/helper";
import { request } from "@/services/response";
import { useRouter } from "next/navigation";

function ListDoctors({
  data,
  page,
  limit,
  filter,
  doctors,
  setPage,
  setDoctors,
  loading: filterLoading,
}) {
  const [loading, setLoading] = useState(false);
  const isLoading = loading || filterLoading;
  const router = useRouter();

  const changePage =async (_, num) => {
    setLoading(true);
      // 👇 اسکرول به بالا با انیمیشن
    window.scrollTo({ top: 0, behavior: "smooth" });

    // 👇 کمی تاخیر برای نمایش نرم‌تر
    await new Promise((res) => setTimeout(res, 300));

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

    setPage(num);
    let params = {
      ...QueryForDoctorsReq(filter),
      page: num,
      limit,
    };
    if (
      data?.name === data.specialty?.name ||
      data?.name === data.category?.name
    ) {
      params.name = "";
      delete params.name;
    }

    request
      .getDoctors(params)
      .then((res) => {
        if (res.data) setDoctors(res.data);
      })
      .catch((err) => {})
      .finally(() => setLoading(false));
  };

  return (
    <>
      <div className="mt-[24px] sm:mt-[37px] md:mt-[50px] lg:mt-[64px] relative">
        {doctors && doctors.length ? (
          <ul className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-[24px]">
            {doctors?.map((doctor, idx) => (
              <ItemDoctor
                key={doctor.id}
                doctor={doctor}
                loading={isLoading}
                priority={idx < 3}
                setDoctors={setDoctors}
              />
            ))}
          </ul>
        ) : (
          <p className="text-center py-10 text-gray-500">
            دکتری برای نمایش وجود ندارد.
          </p>
        )}
      </div>
      <div className="mt-[48px] flex justify-center">
        <PaginationContent
          page={page}
          limit={limit}
          changePage={changePage}
          pageDetail={data?.meta || {}}
        />
      </div>
    </>
  );
}

export default ListDoctors;
