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

import { Stack } from '@mui/material';
import { Page } from '@src/config/react-pdf';

import { getScale, getThreshold } from '../../utils';

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

export const PdfPage = ({
  page,
  zoom,
  variant,
  onUpdatePageNumber = () => null,
  onLoadSuccess = () => null,
  dimensions,
}: PdfPageProps) => {
  const threshHold = useMemo(() => getThreshold(zoom || 0), [zoom]);

  const skipInView =
    (!dimensions.height || !dimensions.width) && variant === 'floating';

  const { ref, inView } = useInView({
    threshold: threshHold,
    skip: skipInView,
  });

  useEffect(() => {
    if (inView) {
      onUpdatePageNumber(page);
    }
  }, [inView, page, onUpdatePageNumber]);

  return (
    <Stack
      key={`page_${page}`}
      sx={{ mb: 2 }}
    >
      <Page
        inputRef={ref}
        scale={getScale(zoom)}
        pageNumber={page}
        onLoadSuccess={onLoadSuccess}
        width={dimensions.width || undefined}
        height={dimensions.height || undefined}
        loading=""
      />
    </Stack>
  );
};

export default PdfPage;
