import { useState } from "react";
import ItemClinic from "./ItemClinic";
import { QueryForClinicsFilter } from "@/helper";
import Pageguide from "@/app/component/Pageguide";
import PaginationContent from "@/app/component/PaginationContent";
import { request } from "@/services/response";
import { useRouter } from "next/navigation";

function List({
  page,
  limit,
  pages,
  setPage,
  clinics,
  selected,
  setFilteredClinics,
}) {
  const listPage = ["کلینیک ها", selected?.city?.name || ""];
  const [loading, setLoading] = useState(false);
  const router = useRouter();

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

    setPage(num);
    const params = {
      ...QueryForClinicsFilter(selected),
      page: num,
      limit,
    };

    request
      .getClinicList(params)
      .then((res) => {
        if (res.data) setFilteredClinics(res.data);
      })
      .catch(() => {})
      //
      .finally(() => setLoading(false));
  };

  return (
    <div className="padding-responsive pt-[20px]">
      <Pageguide list={listPage} />
      {clinics && clinics.length ? (
        <ul
          className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-x-[24px] gap-y-[16px] sm:gap-y-[24px] md:gap-y-[32px] lg:gap-y-[40px] mt-6"
        >
          {clinics.map((item) => (
            <ItemClinic
              data={item}
              key={item.id}
              loading={loading}
              setFilteredClinics={setFilteredClinics}
            />
          ))}
        </ul>
      ) : (
        <div className="text-center py-10 text-gray-500">
          کلینیکی با این عنوان یافت نشد!
        </div>
      )}
      <div className="mt-[48px] flex justify-center">
        <PaginationContent
          page={page}
          limit={limit}
          pageDetail={pages}
          changePage={changePage}
        />
      </div>
    </div>
  );
}

export default List;
