import React from 'react';

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

import { TextArea, TextAreaContainer, TrashCan } from './styled';

const StickyNote: React.SFC<AnnotationElementPropsType> = ({
  id,
  viewport,
  scale,
  obj_attr: { position, content },
  onEdit,
  isEdit,
  onBlur,
  onUpdate,
  onDelete,
}: AnnotationElementPropsType) => {
  const annotRect = rectCalc(position as PositionType, viewport.height, scale);

  const handleClick = (event: React.MouseEvent): void => {
    event.preventDefault();
    onEdit();
  };

  const handleChange = (
    event: React.ChangeEvent<HTMLTextAreaElement>
  ): void => {
    const textValue = event.currentTarget.value;

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

  const handleMove = (moveCoord: CoordType): void => {
    const top = (viewport.height - moveCoord.top) / scale;
    const left = moveCoord.left / scale;

    onUpdate({
      position: {
        top,
        left,
        bottom: top,
        right: left,
      },
    });
  };

  return (
    <>
      <AnnotationContainer
        id={id}
        top={`${annotRect.top}px`}
        left={`${annotRect.left}px`}
        width="auto"
        height="auto"
      >
        <Icon
          glyph="sticky-note-2"
          style={{ width: '30px' }}
          onClick={handleClick}
        />
      </AnnotationContainer>
      {isEdit ? (
        <TextAreaContainer
          top={`${annotRect.top + 36}px`}
          left={`${annotRect.left - 106}px`}
        >
          <TextArea autoFocus defaultValue={content} onChange={handleChange} />
          <TrashCan>
            <Icon glyph="trash-2" onClick={onDelete} />
          </TrashCan>
        </TextAreaContainer>
      ) : null}
      {isEdit ? (
        <OuterRect
          top={annotRect.top}
          left={annotRect.left}
          width={25}
          height={25}
          onMove={handleMove}
          onClick={onBlur}
        />
      ) : null}
    </>
  );
};

export default StickyNote;
