import React, { useRef } from 'react';
import { useTranslation } from 'react-i18next';
import styled from 'styled-components';

import Button from '../components/Button';
import Icon from '../components/Icon';
import { ANNOTATION_TYPE } from '../constants';
import {
  parseAnnotationObject,
  appendUserIdAndDate,
} from '../helpers/annotation';

import useStore from '../store';
import useActions from '../actions';

import { BtnWrapper } from '../global/toolStyled';

type Props = {
  onClickSidebar: (state: string) => void;
};

const FileInput = styled.input`
  display: none;
`;

const ImageTool: React.FC<Props> = ({ onClickSidebar }: Props) => {
  const { t } = useTranslation('sidebar');
  const inputRef = useRef<HTMLInputElement>(null);
  const [{ currentPage, viewport, scale }, dispatch] = useStore();
  const { addAnnots } = useActions(dispatch);

  const handleClick = () => {
    onClickSidebar('add-image');

    if (inputRef.current) {
      inputRef.current.click();
    }
  };

  const getImgDimension = (url: string): Promise<ViewportType> => {
    return new Promise((resolve) => {
      const img = new Image();
      img.src = url;
      img.onload = () => {
        resolve({ width: img.width, height: img.height });
      };
    });
  };

  const handleFiles = (e: React.FormEvent<EventTarget>) => {
    e.stopPropagation();
    e.preventDefault();

    if (inputRef.current && inputRef.current.files) {
      const file = inputRef.current.files[0];

      if (file) {
        const objectUrl = window.URL.createObjectURL(file);

        getImgDimension(objectUrl).then(
          ({ width, height }: ViewportType): void => {
            let objWidth = width;
            let objHeight = height;

            if (width > viewport.width || height > viewport.height) {
              const widthRate = viewport.width / width;
              objWidth = width * widthRate - 100;
              objHeight = height * widthRate - 100;
            }

            const annotData = {
              obj_type: ANNOTATION_TYPE.image,
              obj_attr: {
                page: currentPage,
                position: {
                  top: viewport.height / 2 - objHeight / 2,
                  left: viewport.width / 2 - objWidth / 2,
                  bottom: viewport.height / 2 + objHeight / 2,
                  right: viewport.width / 2 + objWidth / 2,
                },
                src: objectUrl,
              },
            };

            const imageObj = appendUserIdAndDate(
              parseAnnotationObject(annotData, viewport.height, scale),
            );

            addAnnots([imageObj]);
          },
        );
      }
    }
  };

  return (
    <BtnWrapper>
      <Button shouldFitContainer align="left" onClick={handleClick}>
        <Icon glyph="add-image" style={{ marginRight: '10px' }} />
        {t('addImages')}
      </Button>
      <FileInput
        type="file"
        ref={inputRef}
        accept="image/*"
        onChange={handleFiles}
      />
    </BtnWrapper>
  );
};

export default ImageTool;
