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

import OuterRect from '../OuterRect';
import SvgShapeElement from '../SvgShapeElement';

import { rectCalc, parsePositionForBackend } from '../../helpers/position';

import { AnnotationContainer } from '../../global/otherStyled';

const Shape: React.FC<AnnotationElementPropsType> = ({
  id,
  obj_type,
  obj_attr: {
    bdcolor = '',
    fcolor = '',
    bdwidth = 0,
    transparency = 0,
    ftransparency = 0,
    position,
  },
  scale,
  viewport,
  isCollapse,
  onUpdate,
}: AnnotationElementPropsType) => {
  const [moving, setMoving] = useState(false);
  const [localePos, setLocalePos] = useState({
    top: 0,
    left: 0,
    width: 0,
    height: 0,
  });
  const actualbdwidth = bdwidth * scale;

  const handleScaleOrMove = ({
    top,
    left,
    width = 0,
    height = 0,
  }: CoordType): void => {
    setMoving(true);
    const newPosition = {
      top,
      left,
      height,
      width,
    };

    setLocalePos(newPosition);
  };

  const handleMouseUp = () => {
    setMoving(false);
  };

  useEffect(() => {
    const rect = rectCalc(position as PositionType, viewport.height, scale);
    setLocalePos({
      top: rect.top - actualbdwidth / 2,
      left: rect.left - actualbdwidth / 2,
      width: rect.width + actualbdwidth,
      height: rect.height + actualbdwidth,
    });
  }, [viewport, scale]);

  useEffect(() => {
    if (!moving && localePos.width) {
      const newPosition = {
        top: localePos.top,
        left: localePos.left,
        right: localePos.left + localePos.width,
        bottom: localePos.top + localePos.height,
      };

      onUpdate({
        position: parsePositionForBackend(
          obj_type,
          newPosition as PositionType,
          viewport.height,
          scale,
        ),
      });
    }
  }, [moving, localePos]);

  return (
    <>
      <AnnotationContainer
        id={id}
        top={`${localePos.top}px`}
        left={`${localePos.left}px`}
        width={`${localePos.width}px`}
        height={`${localePos.height}px`}
      >
        <SvgShapeElement
          shape={obj_type}
          width={localePos.width}
          height={localePos.height}
          bdcolor={bdcolor}
          transparency={transparency}
          bdwidth={actualbdwidth}
          fcolor={fcolor}
          ftransparency={ftransparency}
        />
      </AnnotationContainer>
      {!isCollapse ? (
        <OuterRect
          top={localePos.top}
          left={localePos.left}
          width={localePos.width}
          height={localePos.height}
          onMove={handleScaleOrMove}
          onScale={handleScaleOrMove}
          onMouseUp={handleMouseUp}
        />
      ) : (
        ''
      )}
    </>
  );
};

export default Shape;
