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

import Icon from '../../components/Icon';
import Button from '../../components/Button';
import Typography from '../../components/Typography';
import ExpansionPanel from '../../components/ExpansionPanel';
import Sliders from '../../components/Sliders';
import ColorSelector from '../../components/ColorSelector';

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

import { getAnnotationWithSelection } from '../../helpers/annotation';
import { Group, Item, SliderWrapper } from '../../global/toolStyled';
import data from './data';

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

const Highlight: React.FunctionComponent<Props> = ({
  isActive,
  onClick,
}: Props) => {
  const [color, setColor] = useState('#fcff36');
  const [type, setType] = useState('highlight');
  const [opacity, setOpacity] = useState(40);

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

  const handleSlide = (value: number): void => {
    setOpacity(value);
  };

  const selectRange = useCallback((e: MouseEvent): void => {
    if (e.target && isActive) {
      const textLayer = (e.target as HTMLElement).parentNode as HTMLElement;
      if (textLayer && textLayer.getAttribute('data-id') === 'text-layer') {
        const newAnnotations = getAnnotationWithSelection({
          color, type, opacity, scale,
        });

        if (newAnnotations && newAnnotations.length) {
          addAnnotation(newAnnotations, true);
        }
      }
    }
  }, [isActive, color, type, opacity, scale]);

  useEffect(() => {
    document.addEventListener('mouseup', selectRange);

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

  return (
    <ExpansionPanel
      label={(
        <Button
          shouldFitContainer
          align="left"
          onClick={onClick}
          isActive={isActive}
        >
          <Icon glyph="highlight" style={{ marginRight: '10px' }} />
          Highlight Tools
        </Button>
      )}
      isActive={isActive}
    >
      <Typography variant="subtitle" style={{ marginTop: '8px' }}>Style</Typography>
      <Group>
        {data.lineType.map(ele => (
          <Item
            key={ele.key}
            selected={type === ele.key}
            onClick={(): void => { setType(ele.key); }}
          >
            <Icon glyph={ele.icon} />
          </Item>
        ))}
      </Group>
      <ColorSelector showTitle color={color} onClick={setColor} />
      <Typography variant="subtitle" style={{ marginTop: '8px' }}>Opacity</Typography>
      <Group>
        <SliderWrapper>
          <Sliders defaultValue={opacity} onChange={handleSlide} />
        </SliderWrapper>
        {`${opacity}%`}
      </Group>
    </ExpansionPanel>
  );
};

export default Highlight;
