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

import ToolbarComponent from '../components/Toolbar';

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

import { scrollIntoView, scaleCheck } from '../helpers/utility';
import { delay } from '../helpers/time';

const Toolbar: React.FC = () => {
  const [
    { totalPage, currentPage, scale, rotation, viewport, displayMode },
    dispatch,
  ] = useStore();
  const [hideToolbar, setHideToolbar] = useState(false);
  let scrollTimeout = 0;

  const {
    setCurrentPage: setCurrentPageAction,
    changeScale,
    changeRotate,
    setSidebar,
  } = useActions(dispatch);

  const setCurrentPage = (num: number): void => {
    if (num > 0) {
      const ele: HTMLElement = document.getElementById(
        `page_${num}`,
      ) as HTMLElement;
      scrollIntoView(ele);
    }
    setCurrentPageAction(num);
    setHideToolbar(false);
  };

  const handleHandClick = (): void => {
    setSidebar('');
  };

  const timer = () => {
    if (scrollTimeout > 0) {
      clearTimeout(scrollTimeout);
      setHideToolbar(false);
    }

    scrollTimeout = setTimeout(() => {
      setHideToolbar(true);
    }, 3000);
  };

  const handleScroll = () => {
    setHideToolbar(false);
  };

  const handleClockwiseRotation = (): void => {
    const r = rotation + 90;
    changeRotate(r);
    setHideToolbar(false);
  };

  const handleCounterclockwiseRotation = (): void => {
    const r = rotation - 90;
    changeRotate(r);
    setHideToolbar(false);
  };

  const handleZoomIn = (): void => {
    changeScale(scaleCheck(scale * 100 + 10));
    setHideToolbar(false);
  };

  const handleZoomOut = (): void => {
    changeScale(scaleCheck(scale * 100 - 10));
    setHideToolbar(false);
  };

  const handleMouseOver = (): void => {
    setHideToolbar(false);
  };

  useEffect(() => {
    const viewer = document.getElementById('pdf_viewer');

    if (viewer) {
      viewer.addEventListener('scroll', handleScroll);
    }

    return () => {
      if (viewer) {
        viewer.removeEventListener('scroll', handleScroll);
      }
    };
  }, [viewport]);

  useEffect(() => {
    if (!hideToolbar) {
      timer();
    }
  }, [hideToolbar]);

  useEffect(() => {
    delay(3000).then(() => {
      setHideToolbar(true);
    });
  }, []);

  return (
    <ToolbarComponent
      totalPage={totalPage}
      currentPage={currentPage}
      setCurrentPage={setCurrentPage}
      changeScale={changeScale}
      handleClockwiseRotation={handleClockwiseRotation}
      handleCounterclockwiseRotation={handleCounterclockwiseRotation}
      handleZoomIn={handleZoomIn}
      handleZoomOut={handleZoomOut}
      handleHandClick={handleHandClick}
      handleMouseOver={handleMouseOver}
      scale={scale}
      viewport={viewport}
      displayMode={displayMode}
      hidden={hideToolbar}
    />
  );
};

export default Toolbar;
