import React, { useEffect, useRef } from 'react';

import { renderPdfPage } from '../../helpers/pdf';
import { TypeRenderingStates, ViewportType } from '../../constants/type';

import {
  PageWrapper, CanvasWrapper, PdfCanvas, AnnotationLayer, TextLayer, LoadingLayer,
} from './styled';

type Props = {
  pageNum: number;
  renderingState?: TypeRenderingStates;
  getPage: () => void;
  viewport: ViewportType;
  rotation: number;
};

const PageView: React.FunctionComponent<Props> = ({
  pageNum,
  getPage,
  viewport,
  renderingState = 'PAUSED',
  rotation,
}) => {
  const rootEle = useRef<HTMLDivElement>(null);
  let page: any = null;

  useEffect(() => {
    if (renderingState === 'RENDERING') {
      renderPage();
    } else if (page && renderingState === 'LOADING') {
      page.cleanup();
    }
  }, [renderingState]);

  useEffect(() => {
    return () => {
      if (page) page.cleanup();
    }
  }, []);

  const renderPage = async () => {
    page = await getPage();

    await renderPdfPage({rootEle: rootEle.current!, page, viewport});
  };

  return (
    <PageWrapper
      ref={rootEle}
      id={`page_${pageNum}`}
      width={viewport.width}
      height={viewport.height}
      rotation={rotation}
    >
      {
        renderingState === 'LOADING' ? (
          <LoadingLayer />
        ) : (
          <>
            <CanvasWrapper>
              <PdfCanvas />
            </CanvasWrapper>
            <TextLayer />
            <AnnotationLayer />
          </>
        )
      }
    </PageWrapper>
  );
};

export default PageView;
