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

import { useInfiniteQuery } from "@tanstack/react-query";
import React, { useEffect, useRef } from "react";
import { fetchProjects } from "@/api/fetchProjects";
import MainProjectCard from "./MainProjectCard";
import { Project } from "@/types/types";
import { useRouter } from "next/navigation";

interface InfiniteProjectsProps {
  initialData: any;
  token: string;
  filters: {
    expertise?: string;
    most_requests?: string;
    most_price?: string;
    age?: string;
    gender?: string;
  };
}

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

  // تبدیل فیلترها به رشته برای استفاده در queryKey
  const filterString = JSON.stringify({
    expertise: filters.expertise || '',
    most_requests: filters.most_requests || '',
    most_price: filters.most_price || '',
    age: filters.age || '',
    gender: filters.gender || ''
  });

  const { 
    data, 
    fetchNextPage, 
    hasNextPage, 
    isFetchingNextPage,
    refetch
  } = useInfiniteQuery({
    queryKey: ['projects', filterString],
    queryFn: ({ pageParam }) => fetchProjects(pageParam, 10, filters, token),
    initialData: {
      pages: [initialData],
      pageParams: [1],
    },
    initialPageParam: 1,
    getNextPageParam: (lastPage, allPages) =>
      lastPage.totalItems > allPages.length * 10 ? allPages.length + 1 : undefined,
    staleTime: 10000, // 10 ثانیه
  });

  // بازخوانی داده‌ها هنگام تغییر فیلترها
  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>
      <div className="mt-5 p-4">
        {data?.pages?.some((page) => page?.projects?.length) ? (
          data.pages.map((page, pageIndex) =>
            page?.projects?.map((item: Project) => (
              <div
                onClick={() => router.push(`/projects/${item?._id}/${item?.title}`)}
                className="cursor-pointer"
                key={`${item._id}-${pageIndex}`}
              >
                <MainProjectCard project={item} />
              </div>
            ))
          )
        ) : (
          <p className="py-16 text-center text-sm text-neutral-500">
            پروژه‌ای برای نمایش وجود ندارد.
          </p>
        )}
      </div>
      <div ref={observerRef} className="h-10 mt-4">
        {isFetchingNextPage && <p>در حال بارگذاری...</p>}
      </div>
    </div>
  );
}