import { type FC, useEffect } from 'react';
import { useInView } from 'react-intersection-observer';

import Box from '@material-hu/mui/Box';

import { Page } from 'src/config/react-pdf';

export type Props = {
  index: number;
  zoomValue?: number;
  onUpdatePageNumber: (pageIndex: number) => void;
  root?: Element | null;
  allowInViewUpdates?: boolean;
  onRenderSuccess?: (pageIndex: number) => void;
};

export const PageInView: FC<Props> = ({
  index,
  zoomValue,
  onUpdatePageNumber,
  root,
  allowInViewUpdates = true,
  onRenderSuccess,
}) => {
  const { ref, inView } = useInView({
    threshold: 0.5,
    root,
  });

  useEffect(() => {
    if (inView && allowInViewUpdates) {
      onUpdatePageNumber(index + 1);
    }
  }, [inView, index, allowInViewUpdates]);

  return (
    <Box
      key={`page_${index + 1}`}
      sx={{ mb: 2 }}
      onClick={e => e.stopPropagation()}
    >
      <Page
        inputRef={ref}
        scale={zoomValue || 1}
        pageNumber={index + 1}
        onRenderSuccess={() => onRenderSuccess?.(index + 1)}
        loading=""
      />
    </Box>
  );
};

export default PageInView;
