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

import Viewer from '../components/Viewer';
import PdfPage from './PdfPage';
import { watchScroll, scaleCheck } from '../helpers/utility';
import useGestureScale from '../hooks/useGestureScale';

import useActions from '../actions';
import useStore from '../store';

type Props = {
  scrollToUpdate: (state: ScrollStateType) => void;
};

let timer = 0;

const PdfPages: React.FC<Props> = ({ scrollToUpdate }: Props) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const [{ totalPage, scale, viewport, rotation }, dispatch] = useStore();
  const { changeScale } = useActions(dispatch);
  const [zoom] = useGestureScale(containerRef);

  useEffect(() => {
    watchScroll(containerRef.current, scrollToUpdate);
  }, []);

  useEffect(() => {
    if (zoom !== 0) {
      const viewer = containerRef.current as HTMLElement;
      viewer.style.transform = `scale(${1 + zoom})`;
      clearTimeout(timer);

      timer = setTimeout(() => {
        const targetScale = Math.round(scale * 100 + zoom * 100);
        changeScale(scaleCheck(targetScale));
        viewer.style.transform = `scale(1)`;
      }, 500);
    }
  }, [zoom]);

  return (
    <Viewer ref={containerRef} viewport={viewport} rotation={rotation}>
      {totalPage &&
        Array(totalPage)
          .fill(1)
          .map((x, i) => <PdfPage key={`page-${i + x}`} index={i + x} />)}
    </Viewer>
  );
};

export default PdfPages;
