/* eslint-disable @typescript-eslint/camelcase */
import React, { useState } from 'react';

import { AnnotationType } from '../constants/type';
import AnnotationComp from '../components/Annotation';
import useCursorPosition from '../hooks/useCursorPosition';

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

type Props = AnnotationType & {
  index: number;
  scale: number;
};

const Annotation: React.FunctionComponent<Props> = ({
  obj_type,
  obj_attr,
  index,
  scale,
}: Props) => {
  const [isCollapse, setCollapse] = useState(true);
  const [isCovered, setMouseOver] = useState(false);
  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
  const [cursorPosition, ref] = useCursorPosition();
  const [{ viewport, annotations }, dispatch] = useStore();
  const { updateAnnotation } = useActions(dispatch);

  const handleClick = (): void => {
    if (isCollapse) {
      setCollapse(false);
      setMousePosition({
        x: cursorPosition.x || 0,
        y: cursorPosition.y || 0,
      });
    }
  };

  const handleBlur = (): void => {
    setCollapse(true);
  };

  const handleMouseOver = (): void => {
    setMouseOver(true);
  };

  const handleMouseOut = (): void => {
    setMouseOver(false);
  };

  const handleUpdate = (data: any): void => {
    if (data.color) {
      annotations[index].obj_attr.bdcolor = data.color;
    }
    if (data.opacity) {
      annotations[index].obj_attr.transparency = data.opacity * 0.01;
    }
    updateAnnotation(annotations);
  };

  const handleDelete = (): void => {
    annotations.splice(index, 1);
    updateAnnotation(annotations);
  };

  return (
    <div
      ref={ref}
      tabIndex={0}
      role="button"
      onFocus={(): void => {}}
      onBlur={handleBlur}
      onMouseDown={handleClick}
      onMouseOver={handleMouseOver}
      onMouseOut={handleMouseOut}
    >
      <AnnotationComp
        obj_type={obj_type}
        obj_attr={obj_attr}
        scale={scale}
        isCollapse={isCollapse}
        isCovered={isCovered}
        mousePosition={mousePosition}
        onUpdate={handleUpdate}
        onDelete={handleDelete}
        viewport={viewport}
      />
    </div>
  );
};

export default Annotation;
