import React, { useMemo, useState } from 'react';
import {  useUploadImageMutation } from '../store/api';
import { useDropzone } from 'react-dropzone';
import { Image } from './Image/Image';
import { Box } from '@mui/material';
import Dnd from './Dnd';

const baseStyle = {
  flex: 1,
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  padding: '20px',
  borderWidth: 2,
  borderRadius: 2,
  borderColor: '#eeeeee',
  borderStyle: 'dashed',
  backgroundColor: '#fafafa',
  color: '#bdbdbd',
  outline: 'none',
  transition: 'border .24s ease-in-out'
};

const focusedStyle = {
  borderColor: '#2196f3'
};

const acceptStyle = {
  borderColor: '#00e676'
};

const rejectStyle = {
  borderColor: '#ff1744'
};

const ImageOnDnd = ({ image, onDelete }) =>
  <Box sx={{ width: '100px', mr: '20px' }} key={image._id}>
    <Image url={image?.url} click={() => onDelete(image)} />
  </Box>

function ImageUploader({ passImages, onChange }) {
  const [images, setImages] = useState(passImages || []);
  const [uploadImage, result] = useUploadImageMutation();
  console.log('result', result);

  // const onDrop = useCallback(acceptedFiles => {
  //   filesUpload(acceptedFiles).then(imagesResponse => {
  //     setImages(images.concat(imagesResponse));
  //   });
  // }, [])

  const updateImages = images => {
    setImages(images);
    onChange(images);
  }

  const onDrop = acceptedFiles => {
    filesUpload(acceptedFiles).then(imagesResponse => {
      updateImages(images.concat(imagesResponse));
    });
  }
  const { getRootProps, getInputProps, isDragActive, isFocused, isDragAccept, isDragReject } = useDropzone({ accept: { 'image/*': [] }, onDrop });

  const style = useMemo(() => ({
    ...baseStyle,
    ...(isFocused ? focusedStyle : {}),
    ...(isDragAccept ? acceptStyle : {}),
    ...(isDragReject ? rejectStyle : {})
  }), [
    isFocused,
    isDragAccept,
    isDragReject
  ]);

  const fileUpload = (file) => {
    const formData = new FormData();
    formData.append('photo', file);
    return uploadImage(formData).then(response => {
      console.log('response', response);
      return Promise.resolve(response.data);
    });
  }

  const filesUpload = (files) => {
    return Promise.all(files.map(fileUpload));
  }
  const deleteImage = image => updateImages(images.filter(i => i != image));

  const localImage = ({ image }) => <ImageOnDnd image={image} onDelete={imgToDelete => deleteImage(imgToDelete)} />

  return (
    <>
      <div {...getRootProps({ style })}>
        <input {...getInputProps()} />
        {
          isDragActive ?
            <p>Drop the files here ...</p> :
            <p>Drag 'n' drop some files here, or click to select files</p>
        }
      </div>
      <Box sx={{ display: 'flex', m: '20px auto 0' }}>
        <Dnd items={images} render={localImage} onChange={images => updateImages(images)} itemProp="image" keyField="_id" horizontal />
      </Box>
    </>
  )
}

export default ImageUploader;