/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import { fetchBillboards } from "@/api/fetchBillboards";
import { IAdvertising } from "@/types/types";
import { useInfiniteQuery } from "@tanstack/react-query";
import React, { useEffect, useRef } from "react";
import MainBillboardCard from "./MainBillboardCard/MainBillboardCard";
import { useRouter } from "next/navigation";
import PageLoader from "@/components/ui/PageLoader";

interface InfiniteBillboardProps {
  initialData: any;
  token: string;
  filters: {
    province?: string;
    city?: string;
    category?: string;
    sort?: string;
    search?: string;
  };
}

export default function InfiniteBillboard({
  initialData,
  filters,
  token,
}: InfiniteBillboardProps) {
  const observerRef = useRef<HTMLDivElement | null>(null);
  const router = useRouter();


  // تبدیل فیلترها به رشته برای استفاده در queryKey
  const filterString = JSON.stringify({
    province: filters.province || "",
    city: filters.city || "",
    category: filters.category || "",
    sort: filters.sort || "",
    search: filters.search || "",
  });

  const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading, refetch } =
    useInfiniteQuery({
      queryKey: ["billboards", filterString],
      queryFn: ({ pageParam }) =>
        fetchBillboards(pageParam, 10, filters, token),
      initialData: {
        pages: [initialData],
        pageParams: [1],
      },
      initialPageParam: 1,
      getNextPageParam: (lastPage, allPages) =>
        lastPage.totalItems > allPages.length * 10
          ? allPages.length + 1
          : undefined,
      staleTime: 60_000,
      gcTime: 300_000,
      retry: 2,
      retryDelay: (attempt) => Math.min(1000 * 2 ** attempt, 8000),
      placeholderData: (prev) => prev,
    });

  // بازخوانی داده‌ها هنگام تغییر فیلترها
  useEffect(() => {
    refetch();
  }, [filterString, refetch]);

  useEffect(() => {
    if (!observerRef.current || !hasNextPage) return;

    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && hasNextPage && !isFetchingNextPage) {
          fetchNextPage();
        }
      },
      {
        threshold: 0.3,
        rootMargin: "100px",
      }
    );

    const currentRef = observerRef.current;
    if (currentRef) observer.observe(currentRef);

    return () => {
      if (currentRef) observer.unobserve(currentRef);
    };
  }, [hasNextPage, fetchNextPage, isFetchingNextPage]);
  return (
    <div>
      {isLoading && !data?.pages?.[0]?.advertisings?.length && (
        <PageLoader className="min-h-[40vh]" />
      )}
      <div className="mt-5 p-4">
        {data?.pages?.map((page, pageIndex) =>
          page?.advertisings?.map((item: IAdvertising) => (
            <div
              onClick={() =>
                router.push(`/billboards/${item?._id}/${item?.title}`)
              }
              className="cursor-pointer"
              key={`${item?._id}-${pageIndex}`}
            >
              <MainBillboardCard billboard={item} />
            </div>
          ))
        )}
      </div>
      <div ref={observerRef} className="mt-4 h-10">
        {isFetchingNextPage && <PageLoader className="min-h-[80px]" />}
      </div>
    </div>
  );
}
