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

import OuterRect from '../OuterRect';
import {
  svgPath,
  bezierCommand,
  controlPoint,
  line,
} from '../../helpers/svgBezierCurve';
import { pointCalc, rectCalcWithPoint, calcViewBox } from '../../helpers/brush';

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

const Ink: React.FC<AnnotationElementPropsType> = ({
  obj_attr: { position, bdcolor, bdwidth = 0, transparency },
  isCollapse,
  onUpdate,
  viewport,
  scale,
  id,
}: AnnotationElementPropsType) => {
  let points: PointType[][] = [];
  let tempRect: HTMLCoordinateType = { top: 0, left: 0, width: 0, height: 0 };
  const borderWidth = bdwidth * scale;

  points = pointCalc(position as PointType[][], viewport.height, scale);
  tempRect = rectCalcWithPoint(points, borderWidth);

  const [rect, setRect] = useState({ top: 0, left: 0, width: 0, height: 0 });

  const handleScaleOrMove = ({
    top,
    left,
    width = 0,
    height = 0,
  }: CoordType): void => {
    const xScaleRate = width / tempRect.width;
    const yScaleRate = height / tempRect.height;
    const xDistance = left - tempRect.left;
    const yDistance = tempRect.top - top;

    const newPosition = (position as PointType[][])[0].map((ele) => ({
      x: (ele.x + xDistance) * (xScaleRate || 1),
      y: (ele.y + yDistance) * (yScaleRate || 1),
    }));

    setRect({
      top,
      left,
      width,
      height,
    });

    onUpdate({
      position: [newPosition],
    });
  };

  useEffect(() => {
    const newPoints = pointCalc(
      position as PointType[][],
      viewport.height,
      scale,
    );
    const newRect = rectCalcWithPoint(newPoints, borderWidth);
    setRect(newRect);
  }, [viewport, scale]);

  return (
    <>
      <AnnotationContainer
        id={id}
        top={`${rect.top}px`}
        left={`${rect.left}px`}
        width={`${rect.width}px`}
        height={`${rect.height}px`}
      >
        <SVG viewBox={calcViewBox(tempRect, borderWidth)}>
          {points.map((ele: PointType[], index: number) => {
            const key = `${id}_path_${index}`;
            return (
              <path
                key={key}
                d={svgPath(
                  ele as PointType[],
                  bezierCommand(controlPoint(line, 0.2)),
                )}
                fill="none"
                stroke={bdcolor}
                strokeWidth={borderWidth}
                strokeOpacity={transparency}
              />
            );
          })}
        </SVG>
      </AnnotationContainer>
      {!isCollapse ? (
        <OuterRect
          top={rect.top}
          left={rect.left}
          width={rect.width}
          height={rect.height}
          onMove={handleScaleOrMove}
          onScale={handleScaleOrMove}
        />
      ) : (
        ''
      )}
    </>
  );
};

export default Ink;
