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

import Icon from '../components/Icon';
import Button from '../components/Button';
import ExpansionPanel from '../components/ExpansionPanel';
import HighlightOption from '../components/HighlightOption';

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

import { getMarkupWithSelection } from '../helpers/markup';

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

const HighlightTools: React.FC<Props> = ({
  title,
  isActive,
  onClick,
}: Props) => {
  const [data, setData] = useState({
    type: 'highlight',
    color: '#FCFF36',
    opacity: 40,
  });

  const [{ scale }, dispatch] = useStore();
  const { addAnnots } = useActions(dispatch);

  const setDataState = (obj: OptionPropsType): void => {
    setData(prev => ({
      ...prev,
      ...obj,
    }));
  };

  const selectRange = useCallback(
    (e: MouseEvent | TouchEvent): void => {
      if (e.target && isActive) {
        const textLayer = (e.target as HTMLElement).parentNode as HTMLElement;
        if (textLayer && textLayer.getAttribute('data-id') === 'text-layer') {
          const newMarkup = getMarkupWithSelection({
            ...data,
            scale,
          });

          if (newMarkup) {
            addAnnots([newMarkup]);
          }
        }
      }
    },
    [isActive, data, scale]
  );

  useEffect(() => {
    if (isActive) {
      document.addEventListener('touchend', selectRange);
      document.addEventListener('mouseup', selectRange);
    }

    return (): void => {
      document.removeEventListener('touchend', selectRange);
      document.removeEventListener('mouseup', selectRange);
    };
  }, [isActive, selectRange]);

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

  return (
    <ExpansionPanel label={Label} isActive={isActive} showBottomBorder>
      <HighlightOption {...data} setDataState={setDataState} />
    </ExpansionPanel>
  );
};

export default HighlightTools;
