import React from 'react';

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

import { TextBox } from './styled';

const TextField: React.FC<AnnotationElementPropsType> = ({
  id,
  obj_type,
  obj_attr: { position, style },
  scale,
  viewport,
  isCollapse,
  onUpdate,
}: AnnotationElementPropsType) => {
  const annotRect = rectCalc(position as PositionType, viewport.height, scale);

  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,
      ),
    });
  };

  let formType = obj_type;
  if (obj_type === 'checkbox' && style === '1') {
    formType = 'radio';
  }

  return (
    <>
      <AnnotationContainer
        id={id}
        top={`${annotRect.top}px`}
        left={`${annotRect.left}px`}
        width={`${annotRect.width}px`}
        height={`${annotRect.height}px`}
      >
        <TextBox type={formType}>
          {obj_type === 'textfield' ? '輸入框' : ''}
        </TextBox>
      </AnnotationContainer>
      {!isCollapse ? (
        <OuterRect
          top={annotRect.top}
          left={annotRect.left}
          width={annotRect.width}
          height={annotRect.height}
          onMove={handleScaleOrMove}
          onScale={handleScaleOrMove}
        />
      ) : (
        ''
      )}
    </>
  );
};

export default TextField;
