/* eslint-disable @typescript-eslint/no-explicit-any */
import { useEffect, useRef } from "react";
import { useInfiniteQuery } from "@tanstack/react-query";
import useAxios from "@/hooks/useAxios";

interface FetchParams {
  endpoint: string;
  queryKey: (string | number)[]; 
  params?: Record<string, any>;
  limit?: number;
}

const useInfiniteScroll = ({
  endpoint,
  queryKey,
  params = {},
  limit = 10,
}: FetchParams) => {
  const { request } = useAxios();
  const containerRef = useRef<HTMLDivElement>(null);

  const fetchData = async ({ pageParam = 1 }) => {
    const queryParams = new URLSearchParams({
      ...params,
      limit: limit.toString(),
      page: pageParam.toString(),
    });
    const data = await request<any>(
      "GET",
      `${endpoint}?${queryParams.toString()}`
    );
    return data || [];
  };

  const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading, refetch } =
    useInfiniteQuery({
      queryKey,
      queryFn: ({ pageParam }) => fetchData({ pageParam }),
      initialPageParam: 1,
      getNextPageParam: (lastPage, allPages) =>
        lastPage.totalPages > allPages.length ? allPages.length + 1 : undefined,
    });

  useEffect(() => {
    const handleScroll = () => {
      const container = containerRef.current || document.documentElement;
      if (!container || isFetchingNextPage) return;

      const { scrollTop, scrollHeight, clientHeight } = container;
      if (scrollTop + clientHeight >= scrollHeight - 50 && hasNextPage) {
        fetchNextPage();
      }
    };

    const containerElement = containerRef.current;
    if (containerElement) {
      containerElement.addEventListener("scroll", handleScroll);
    } else {
      window.addEventListener("scroll", handleScroll);
    }

    return () => {
      if (containerElement) {
        containerElement.removeEventListener("scroll", handleScroll);
      } else {
        window.removeEventListener("scroll", handleScroll);
      }
    };
  }, [hasNextPage, fetchNextPage, isFetchingNextPage]);

  return { data, containerRef, isFetchingNextPage, isLoading, refetch };
};

export default useInfiniteScroll;