import { useCallback, useEffect, useState } from 'react';

const useInfiniteScroll = (
  paginationData: any,
  setShouldPerformAction: Function,
  tableScrolling: any
) => {
  const [page, setPage] = useState(1);
  const [scrollActivated, setScrollActivated] = useState(false);
  const debounce = (func: Function, wait: number) => {
    let timeout: ReturnType<typeof setTimeout>;
    return (...args: any[]) => {
      clearTimeout(timeout);
      timeout = setTimeout(() => func(...args), wait);
    };
  };

  const handleInfiniteScroll = useCallback(
    debounce(() => {
      setScrollActivated(true);
      const element = document.getElementById(tableScrolling);
      if (element) {
        const { scrollHeight, offsetHeight, scrollTop } = element;
        let totalPages;
        if (paginationData) {
          totalPages = JSON.parse(paginationData).total_pages;
        }
        if (
          offsetHeight + scrollTop >= scrollHeight &&
          totalPages >= page &&
          totalPages > page
        ) {
          setShouldPerformAction(true);
          setPage(prev => prev + 1);
        }
      }
    }, 700),
    [paginationData, page, setShouldPerformAction]
  );
  useEffect(() => {
    const element = document.getElementById(tableScrolling);
    if (element) {
      element.addEventListener('scroll', handleInfiniteScroll);
    }
    return () => {
      if (element) {
        element.removeEventListener('scroll', handleInfiniteScroll);
      }
    };
  }, [handleInfiniteScroll]);
  return { page, scrollActivated };
};

export default useInfiniteScroll;
