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

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

interface InfiniteSearchProps {
  token: string;
  initialData: any;
  filters: {
    type?: string;
    search?: string;
  };
}

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

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

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

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

  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 flex flex-col gap-4">
        {data?.pages?.map((page, pageIndex) =>
          page?.result?.map((item: any) => {
            if (filters?.type === "user" || filters?.type === "employer") {
              return (
                <SearchCard 
                  key={`${(item as User)._id}-${pageIndex}`} 
                  user={item as User} 
                />
              );
            } else {
              return (
                <div
                  key={`${(item as Project)._id}-${pageIndex}`}
                  onClick={() => {
                    router.push(`/projects/${item?._id}/${item?.title}`);
                  }}
                  className="cursor-pointer"
                >
                  <MainProjectCard project={item as Project} />
                </div>
              );
            }
          })
        )}
      </div>
      <div ref={observerRef} className="h-10 mt-4">
        {isFetchingNextPage && <p>در حال بارگذاری...</p>}
      </div>
    </div>
  );
}