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

import Watermark from '../Watermark';
import { renderPdfPage } from '../../helpers/pdf';

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

type Props = {
  pageNum: number;
  renderingState?: RenderingStateType;
  getPage?: () => Promise<any>;
  viewport: ViewportType;
  rotation?: number;
  scale: number;
  annotations?: React.ReactNode[];
  drawing?: React.ReactNode[];
  watermark?: WatermarkType;
  setTextDivs: (pageNum: number, elements: HTMLElement[]) => void;
  currentPage: number;
};

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

  const renderPage = async (): Promise<any> => {
    if (getPage) {
      getPage().then(obj => {
        setPdfPage(obj);

        const setTextDivsWithPage = (elements: HTMLElement[]) => {
          if (currentPage === pageNum) {
            setTextDivs(pageNum, elements);
          }
        };

        if (rootEle.current) {
          renderPdfPage({
            rootEle: rootEle.current,
            pdfPage: obj,
            viewport,
            setRenderTask,
            setTextDivs: setTextDivsWithPage,
          });
        }
      });
    }
  };

  useEffect(() => {
    if (pdfPage) {
      pdfPage.cleanup();
    }
    if (renderTask) {
      renderTask.cancel();
    }

    if (renderingState === 'RENDERING') {
      renderPage();
    }
  }, [currentPage, renderingState, viewport]);

  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;
