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,
  appendUserIdAndDate,
} from '../helpers/annotation';

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

import { BtnWrapper } from '../global/toolStyled';

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

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

  const addTextfield = (
    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.textfield,
      obj_attr: {
        page: pageNum as number,
        position: {
          top: coordinate.y,
          left: coordinate.x,
          bottom: coordinate.y + 50,
          right: coordinate.x + 150,
        },
      },
    };

    const newTextfield = appendUserIdAndDate(
      parseAnnotationObject(annotData, viewport.height, scale),
    );

    addAnnots([newTextfield]);
  };

  const handleClick = useCallback(
    (event: MouseEvent | TouchEvent): void => {
      const pageEle = (event.target as HTMLElement).parentNode as HTMLElement;

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

  useEffect(() => {
    if (isActive) {
      document.addEventListener('click', handleClick);
    }

    return () => {
      document.removeEventListener('click', handleClick);
    };
  }, [isActive]);

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

export default TextfieldTool;
