import { React } from "react";
import { useSelector, useDispatch } from 'react-redux';
import { updateImages } from '../../database/images';
import styled from 'styled-components';
import ImageEditor from '@toast-ui/react-image-editor';

import 'tui-image-editor/dist/tui-image-editor.css';

const Container = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
`;

const Block = styled.div`
  position: relative;
`;

const Button = styled.button`
  position: absolute;
  top: 12px;
  right: 12px;
  width: 40px;
  height: 40px;
  font-size: 20px;
  background: red;
  color: #fff;
  border: 0;
  cursor: pointer;
  z-index: 9;

  &.save {
    top: unset;
    bottom: 12px;
    background: green;
  }
`;

function ImageEditors({ image, show, setShow }) {
  if (image === null) return;

  const dispatch = useDispatch();
  const state = useSelector((state) => state.images.value);

  const imageEditorsSave = () => {
    const images = state;
    const canvas = document.querySelector(".lower-canvas");
    const dataURL = canvas.toDataURL(image.type);

    const newImage = { ...image, 'dataURL': dataURL, 'time': Date.now() };
    const newState = { ...images, [image.id]: newImage }
    dispatch(updateImages(newState));
    setShow(false);
  }

  const imageEditorsClose = () => {
    setShow(false);
  }

  return (
    <>
      {show &&
        <Container >
          <Block>
            <ImageEditor
              includeUI={{
                loadImage: {
                  path: image.dataURL,
                  name: 'Edited image',
                },
                menu: ['shape', 'filter', 'text', 'crop', 'flip', 'rotate', 'draw', 'icon', 'mask'],
                uiSize: {
                  width: '1200px',
                  height: '600px',
                },
                menuBarPosition: 'right',
              }}
              cssMaxHeight={500}
              cssMaxWidth={700}
              selectionStyle={{
                cornerSize: 20,
                rotatingPointOffset: 70,
              }}
              usageStatistics={true}
            />
            <Button type="button" onClick={imageEditorsClose}>X</Button>
            <Button type="button" className="save" onClick={imageEditorsSave}>✓</Button>
          </Block>
        </Container>
      }
    </>
  )
}

export default ImageEditors