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

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

import { AnnotationContainer } from '../../global/otherStyled';
import { TextWrapper, Input } from './styled';

const FreeText: React.SFC<AnnotationElementPropsType> = ({
  obj_type,
  obj_attr: { content, position, fontname, fontsize, textcolor },
  scale,
  viewport,
  isCollapse,
  isEdit,
  onEdit,
  onUpdate,
  onBlur,
}: AnnotationElementPropsType) => {
  const inputRef = useRef<HTMLInputElement>(null);
  const annotRect = rectCalc(position as PositionType, viewport.height, scale);

  const handleChange = (event: React.FormEvent<HTMLInputElement>): void => {
    const textValue = event.currentTarget.value;
    const fontWidth = textValue.length * ((fontsize as number) * 0.9 || 1);
    const newPosition = { ...(position as PositionType) };
    newPosition.right = newPosition.left + fontWidth;

    onUpdate({
      content: textValue,
      position: newPosition,
    });
  };

  const handleScaleOrMove = ({
    top,
    left,
    width = 0,
    height = 0,
  }: CoordType): void => {
    const newPosition = {
      top,
      left,
      bottom: top + (height || annotRect.height),
      right: left + (width || annotRect.width),
    };

    onUpdate({
      fontsize: (height || annotRect.height) / scale,
      position: parsePositionForBackend(
        obj_type,
        newPosition,
        viewport.height,
        scale
      ),
    });
  };

  const styles = {
    fontFamily: fontname,
    fontSize: fontsize ? fontsize * scale : 0,
    color: textcolor,
  };

  useEffect(() => {
    if (isEdit) {
      setTimeout(() => {
        if (inputRef.current) inputRef.current.focus();
      }, 100);
    }
  }, [isEdit]);

  return (
    <div>
      <AnnotationContainer
        top={`${annotRect.top}px`}
        left={`${annotRect.left}px`}
        width={`${annotRect.width + 2}px`}
        height={`${annotRect.height + 8}px`}
      >
        {isEdit ? (
          <Input
            ref={inputRef}
            defaultValue={content}
            onChange={handleChange}
            onBlur={onBlur}
            style={styles}
          />
        ) : (
          <TextWrapper style={styles}>{content}</TextWrapper>
        )}
      </AnnotationContainer>
      {!isCollapse ? (
        <OuterRect
          top={annotRect.top}
          left={annotRect.left}
          width={annotRect.width}
          height={annotRect.height}
          onMove={handleScaleOrMove}
          onScale={handleScaleOrMove}
          onDoubleClick={onEdit}
        />
      ) : (
        ''
      )}
    </div>
  );
};

export default FreeText;
