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

import { ANNOTATION_TYPE } from '../constants';
import Button from '../components/Button';
import Icon from '../components/Icon';
import { getAbsoluteCoordinate } from '../helpers/position';
import { parseAnnotationObject } from '../helpers/annotation';
import { BtnWrapper } from '../global/toolStyled';

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

type Props = {
  title: string;
  isActive: boolean;
  onClick: () => void;
};

const StickyNoteTools: React.FC<Props> = ({
  title,
  isActive,
  onClick,
}: Props) => {
  const [{ viewport, scale }, dispatch] = useStore();
  const { addAnnots } = useActions(dispatch);

  const addStickyNote = (
    pageEle: HTMLElement,
    event: MouseEvent | TouchEvent
  ): void => {
    const pageNum = pageEle.getAttribute('data-page-num') || 0;
    const coordinate = getAbsoluteCoordinate(pageEle, event);

    const annotData = {
      obj_type: ANNOTATION_TYPE.text,
      obj_attr: {
        page: pageNum as number,
        position: {
          top: coordinate.y,
          left: coordinate.x,
          bottom: coordinate.y + 20,
          right: coordinate.x + 20,
        },
        content: '',
      },
    };
    const stickyNote = parseAnnotationObject(annotData, viewport.height, scale);

    addAnnots([stickyNote]);
  };

  const handleMouseDown = useCallback(
    (event: MouseEvent | TouchEvent): void => {
      // event.preventDefault();

      const pageEle = (event.target as HTMLElement).parentNode as HTMLElement;

      if (pageEle.hasAttribute('data-page-num')) {
        addStickyNote(pageEle, event);
      }
    },
    [viewport, scale]
  );

  useEffect(() => {
    const pdfViewer = document.getElementById('pdf_viewer') as HTMLDivElement;

    if (isActive && pdfViewer) {
      window.addEventListener('touchstart', handleMouseDown);
      window.addEventListener('mousedown', handleMouseDown);
    }

    return (): void => {
      if (pdfViewer) {
        window.removeEventListener('touchstart', handleMouseDown);
        window.removeEventListener('mousedown', handleMouseDown);
      }
    };
  }, [isActive, handleMouseDown]);

  return (
    <BtnWrapper>
      <Button
        shouldFitContainer
        align="left"
        onClick={onClick}
        isActive={isActive}
      >
        <Icon glyph="sticky-note" style={{ marginRight: '10px' }} />
        {title}
      </Button>
    </BtnWrapper>
  );
};

export default StickyNoteTools;
