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

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

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

import { Dimensions } from 'src/hooks/useDimensions';
import { getScalePdf } from 'src/utils/files';

export type PdfPageWithObserverProps = {
  index: number;
  zoomValue?: number;
  onUpdatePageNumber: Function;
  onLoadSuccess: (page: unknown) => void;
  dimensions: Dimensions;
};

export const PdfPageWithObserver: FC<PdfPageWithObserverProps> = props => {
  const { index, zoomValue, onUpdatePageNumber, onLoadSuccess, dimensions } =
    props;

  const { ref, inView } = useInView({
    threshold: 0.5,
  });

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

  return (
    <Box
      key={`page_${index + 1}`}
      sx={{ mb: 2 }}
    >
      <Page
        inputRef={ref}
        scale={zoomValue ? getScalePdf(zoomValue) : 1}
        pageNumber={index + 1}
        onLoadSuccess={onLoadSuccess}
        width={dimensions.width}
        height={dimensions.height}
        loading=""
      />
    </Box>
  );
};

export default PdfPageWithObserver;
