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

import Watermark from '../Watermark';
import { renderPdfPage } from '../../helpers/pdf';
import {
  RenderingStateType, ViewportType, WatermarkType,
} from '../../constants/type';

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

type Props = {
  pageNum: number;
  renderingState?: RenderingStateType;
  getPage?: () => void;
  viewport: ViewportType;
  rotation?: number;
  scale: number;
  annotations?: React.ReactNode[];
  drawing?: React.ReactNode[];
  watermark?: WatermarkType;
};

const PageView: React.FC<Props> = ({
  pageNum,
  getPage,
  viewport,
  renderingState = 'PAUSED',
  rotation,
  scale,
  annotations = [],
  watermark = {},
}: Props) => {
  const rootEle = useRef<HTMLDivElement | null>(null);
  let pdfPage: any = null;

  const renderPage = async (): Promise<any> => {
    if (getPage) {
      pdfPage = await getPage();

      if (rootEle.current) {
        await renderPdfPage({
          rootEle: rootEle.current,
          pdfPage,
          viewport,
        });
      }
    }
  };

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

  useEffect(() => (): void => {
    if (pdfPage) pdfPage.cleanup();
  }, []);

  return (
    <PageWrapper
      ref={rootEle}
      id={`page_${pageNum}`}
      data-page-num={pageNum}
      width={viewport.width}
      height={viewport.height}
      rotation={rotation}
    >
      {
        renderingState === 'LOADING' ? (
          <>
            <TextLayer data-id="text-layer" />
          </>
        ) : (
          <>
            <PdfCanvas />
            {watermark.text || watermark.imagepath ? (
              <WatermarkLayer>
                <Watermark
                  viewScale={scale}
                  {...watermark}
                />
              </WatermarkLayer>
            ) : ''}
            <TextLayer data-id="text-layer" />
            <AnnotationLayer data-id="annotation-layer">
              {annotations}
            </AnnotationLayer>
          </>
        )
      }
    </PageWrapper>
  );
};

export default PageView;
