import { React, useState } from "react";
import { Tooltip } from 'react-tooltip';
import { useSelector, useDispatch } from 'react-redux';
import { updateImages } from '../../database/images';
import { updateDatabase } from '../../database/database';
import styled from 'styled-components';
import ImageUploading from 'react-images-uploading';
import ImageEditors from "./ImageEditor";

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

const Box = styled.div`
  position: relative;
  max-width: 1000px;
`;

const Close = styled.button`
  position: absolute;
  top: 0;
  right: 0;
  width: 40px;
  height: 40px;
  background-color: red;
  color: #fff;
  border: 0;
  z-index: 1;
  font-size: 18px;
  font-weight: 700;
  cursor: pointer;
`;

const Button = styled.button`
  color: #fff;
  pointer-events: ${(props) => props.$enable ? 'unset' : 'none'};
`;

function ImageUpload({ id, setVisible }) {
  const state = useSelector((state) => state.images.value);
  const database = useSelector((state) => state.database.value);

  const images = Object.entries(state).map(img => img[1]);
  const dispatch = useDispatch();

  const [show, setShow] = useState(false);
  const [editImage, setEditImage] = useState(null);
  const [choseImage, setChoseImage] = useState(false);
  const maxNumber = 20;

  const hideModal = () => {
    setVisible(false);
    setChoseImage(false);
    document.querySelector('body').style.overflow = 'auto';
  }

  const onChange = (imageList, addUpdateIndex) => {
    const newImages = imageList.map(img => {
      const id = img.id ? img.id : 'image-' + img.file.lastModified;

      const image = img.id ? img : {
        'id': id,
        'name': img.file.name,
        'dataURL': img.dataURL,
        'size': img.file.size,
        'type': img.file.type,
        'time': img.file.lastModified
      };
      return [id, image];
    })

    const newImageList = Object.fromEntries(newImages);
    dispatch(updateImages(newImageList));

    const imagesTotal = Object.keys(newImageList).length;
    if (addUpdateIndex && addUpdateIndex[0] + 1 === imagesTotal) {
      setTimeout(function () {
        const target = document.querySelector('.ld-image-upload-item:last-child');
        target.scrollIntoView({ behavior: "smooth", block: "end", inline: "end" });
      }, 100)
    }
  }

  const editImages = (index) => {
    setEditImage(images[index]);
    setShow(true);
  }

  const onSelect = (index) => {
    const target = document.querySelector(`.ld-image-upload-img[data-index='${index}']`);

    if (target.classList.contains('selected')) {
      target.classList.remove('selected');
      setChoseImage(false);
      return;
    }

    document.querySelectorAll('.ld-image-upload-img').forEach(img => {
      img.classList.remove("selected");
    });

    target.classList.add("selected");
    setChoseImage(images[index].dataURL);
  }

  const onSubmit = () => {
    const target = database[id];
    const targetAttrs = target.attributes;
    const targetStyles = target.styles;
    const targetImage = target.type === "image";

    const newParams = targetImage ? { ...targetAttrs, src: choseImage } : { ...targetStyles, background: `url(${choseImage})` };
    const newData = targetImage ? { ...target, attributes: newParams } : { ...target, styles: newParams };
    const newDatabase = { ...database, [id]: newData };

    dispatch(updateDatabase(newDatabase));
    hideModal();
  }

  return (
    <>
      <Container>
        <Box>
          <Close onClick={hideModal}>X</Close>

          <ImageUploading multiple value={images} onChange={onChange} maxNumber={maxNumber} dataURLKey="dataURL" >
            {({
              imageList,
              onImageUpload,
              onImageRemoveAll,
              onImageUpdate,
              onImageRemove,
              isDragging,
              dragProps,
            }) => (
              <div className="ld-image-upload-container">
                <div>
                  <div className="ld-image-upload-zone" style={isDragging ? { color: 'red' } : undefined} onClick={onImageUpload} {...dragProps}>
                    <svg viewBox="0 0 1024 1024" focusable="false" data-icon="inbox" width="2em" height="2em" fill="currentColor" aria-hidden="true">
                      <path d="M885.2 446.3l-.2-.8-112.2-285.1c-5-16.1-19.9-27.2-36.8-27.2H281.2c-17 0-32.1 11.3-36.9 27.6L139.4 443l-.3.7-.2.8c-1.3 4.9-1.7 9.9-1 14.8-.1 1.6-.2 3.2-.2 4.8V830a60.9 60.9 0 0060.8 60.8h627.2c33.5 0 60.8-27.3 60.9-60.8V464.1c0-1.3 0-2.6-.1-3.7.4-4.9 0-9.6-1.3-14.1zm-295.8-43l-.3 15.7c-.8 44.9-31.8 75.1-77.1 75.1-22.1 0-41.1-7.1-54.8-20.6S436 441.2 435.6 419l-.3-15.7H229.5L309 210h399.2l81.7 193.3H589.4zm-375 76.8h157.3c24.3 57.1 76 90.8 140.4 90.8 33.7 0 65-9.4 90.3-27.2 22.2-15.6 39.5-37.4 50.7-63.6h156.5V814H214.4V480.1z"></path>
                    </svg>
                    Click or Drop here
                  </div>
                </div>

                <div>
                  <div className="ld-image-upload-list">
                    {!imageList.length && <div className="ld-image-upload-list__empty"><p><b>Thư viện ảnh trống.</b></p> Vui lòng tải thêm ảnh lên để sử dụng.</div>}

                    {imageList && imageList.map((image, index) => (
                      <div className="ld-image-upload-item" key={index}>
                        <div className="ld-image-upload-img" data-index={index} onClick={() => onSelect(index)}>
                          <div className="ld-img-block">
                            <img src={image['dataURL']} alt="" width="140" className="ld-img-content" />
                          </div>
                        </div>

                        <div className="ld-image-upload-wrapper">
                          <button
                            type="button"
                            className="ld-image-upload-btn ld-image-upload-btn__tool"
                            onClick={() => editImages(index)}
                            data-tooltip-id="ld-images-tooltip"
                            data-tooltip-content="Xem, chỉnh sửa"
                            data-tooltip-place="top"
                          >
                            <svg xmlns="http://www.w3.org/2000/svg" height="16" width="16" viewBox="0 0 512 512">
                              <path d="M441 58.9L453.1 71c9.4 9.4 9.4 24.6 0 33.9L424 134.1 377.9 88 407 58.9c9.4-9.4 24.6-9.4 33.9 0zM209.8 256.2L344 121.9 390.1 168 255.8 302.2c-2.9 2.9-6.5 5-10.4 6.1l-58.5 16.7 16.7-58.5c1.1-3.9 3.2-7.5 6.1-10.4zM373.1 25L175.8 222.2c-8.7 8.7-15 19.4-18.3 31.1l-28.6 100c-2.4 8.4-.1 17.4 6.1 23.6s15.2 8.5 23.6 6.1l100-28.6c11.8-3.4 22.5-9.7 31.1-18.3L487 138.9c28.1-28.1 28.1-73.7 0-101.8L474.9 25C446.8-3.1 401.2-3.1 373.1 25zM88 64C39.4 64 0 103.4 0 152V424c0 48.6 39.4 88 88 88H360c48.6 0 88-39.4 88-88V312c0-13.3-10.7-24-24-24s-24 10.7-24 24V424c0 22.1-17.9 40-40 40H88c-22.1 0-40-17.9-40-40V152c0-22.1 17.9-40 40-40H200c13.3 0 24-10.7 24-24s-10.7-24-24-24H88z" />
                            </svg>
                          </button>

                          <button
                            type="button"
                            className="ld-image-upload-btn ld-image-upload-btn__tool"
                            onClick={() => onImageUpdate(index)}
                            data-tooltip-id="ld-images-tooltip"
                            data-tooltip-content="Thay thế"
                            data-tooltip-place="top"
                          >
                            <svg xmlns="http://www.w3.org/2000/svg" height="14" width="17.5" viewBox="0 0 640 512">
                              <path d="M144 480C64.5 480 0 415.5 0 336c0-62.8 40.2-116.2 96.2-135.9c-.1-2.7-.2-5.4-.2-8.1c0-88.4 71.6-160 160-160c59.3 0 111 32.2 138.7 80.2C409.9 102 428.3 96 448 96c53 0 96 43 96 96c0 12.2-2.3 23.8-6.4 34.6C596 238.4 640 290.1 640 352c0 70.7-57.3 128-128 128H144zm79-217c-9.4 9.4-9.4 24.6 0 33.9s24.6 9.4 33.9 0l39-39V392c0 13.3 10.7 24 24 24s24-10.7 24-24V257.9l39 39c9.4 9.4 24.6 9.4 33.9 0s9.4-24.6 0-33.9l-80-80c-9.4-9.4-24.6-9.4-33.9 0l-80 80z" />
                            </svg>
                          </button>

                          <button
                            type="button"
                            className="ld-image-upload-btn ld-image-upload-btn__tool"
                            onClick={() => { if (confirm('Are you sure?')) { onImageRemove(index) } }}
                            data-tooltip-id="ld-images-tooltip"
                            data-tooltip-content="Xóa"
                            data-tooltip-place="top"
                          >
                            <svg xmlns="http://www.w3.org/2000/svg" height="14" width="12.25" viewBox="0 0 448 512">
                              <path d="M170.5 51.6L151.5 80h145l-19-28.4c-1.5-2.2-4-3.6-6.7-3.6H177.1c-2.7 0-5.2 1.3-6.7 3.6zm147-26.6L354.2 80H368h48 8c13.3 0 24 10.7 24 24s-10.7 24-24 24h-8V432c0 44.2-35.8 80-80 80H112c-44.2 0-80-35.8-80-80V128H24c-13.3 0-24-10.7-24-24S10.7 80 24 80h8H80 93.8l36.7-55.1C140.9 9.4 158.4 0 177.1 0h93.7c18.7 0 36.2 9.4 46.6 24.9zM80 128V432c0 17.7 14.3 32 32 32H336c17.7 0 32-14.3 32-32V128H80zm80 64V400c0 8.8-7.2 16-16 16s-16-7.2-16-16V192c0-8.8 7.2-16 16-16s16 7.2 16 16zm80 0V400c0 8.8-7.2 16-16 16s-16-7.2-16-16V192c0-8.8 7.2-16 16-16s16 7.2 16 16zm80 0V400c0 8.8-7.2 16-16 16s-16-7.2-16-16V192c0-8.8 7.2-16 16-16s16 7.2 16 16z" />
                            </svg>
                          </button>

                        </div>
                      </div>
                    ))}

                  </div>

                  <div className="ld-image-upload-wrapper ld-image-upload-wrapper__bottom">
                    <button type="button" className="ld-image-upload-btn remove-all" onClick={() => { if (confirm('Are you sure?')) { onImageRemoveAll() } }}>Remove all images</button>
                    <Button $enable={choseImage} type="button" className="ld-image-upload-btn submit" onClick={() => { if (confirm('Are you sure?')) { onSubmit() } }}>Replace</Button>
                  </div>
                </div>
              </div>
            )}
          </ImageUploading>

          <ImageEditors image={editImage} show={show} setShow={setShow} />
        </Box>

        <Tooltip id="ld-images-tooltip" />
      </Container>
    </>
  );
}

export default ImageUpload