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

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

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

let pdfPage: any = null;

type Props = {
  pageNum: number;
  renderingState: RenderingStateType;
  getPage: () => Promise<any>;
  viewport: ViewportType;
  rotation: number;
  scale: number;
  annotations: React.ReactNode[];
  watermark: WatermarkType;
  queryString: string;
  matchesMap: MatchType[];
};

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

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

        const setTextDivs = (elements: HTMLElement[]) => {
          if (queryString && matchesMap.length) {
            matchesMap.forEach(item => {
              if (pageNum === item.page) {
                const id = `${item.page}_${item.index}`;
                renderMatches(elements, getPage, item.index, queryString, id);
              }
            });
          }
        };

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

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

  useEffect(() => {
    if (queryString === '' && !matchesMap.length) {
      renderPage();
    }
  }, [queryString, matchesMap]);

  return (
    <PageWrapper
      ref={rootEle}
      id={`page_${pageNum}`}
      data-page-num={pageNum}
      width={viewport.width}
      height={viewport.height}
      rotation={rotation}
    >
      {renderingState === 'LOADING' ? (
        <Inner>載入中...</Inner>
      ) : (
        <>
          <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;
