import { useEffect, useRef } from 'react';

import Button from '@mui/lab/LoadingButton';
import { IconProgress } from '@tabler/icons-react';

import { type InfiniteListLoaderProps } from './types';

const InfiniteListLoader = ({
  onLoadMore,
  containerRef,
  ...props
}: InfiniteListLoaderProps) => {
  const ioInstance = useRef<IntersectionObserver | null>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);

  useEffect(() => {
    const handleIntersection = (entries: IntersectionObserverEntry[]) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          onLoadMore();
        }
      });
    };

    if (containerRef.current) {
      ioInstance.current = new IntersectionObserver(handleIntersection, {
        root: containerRef.current,
      });

      if (buttonRef.current) {
        ioInstance.current.observe(buttonRef.current);
      }

      return () => {
        if (ioInstance.current) {
          ioInstance.current.disconnect();
        }
      };
    }
  }, [onLoadMore]);

  return (
    <Button
      ref={buttonRef}
      variant="secondary"
      size="small"
      onClick={onLoadMore}
      endIcon={props?.loading ? undefined : <IconProgress size={16} />}
      {...props}
    />
  );
};

export type { InfiniteListLoaderProps };

export default InfiniteListLoader;
