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

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'
};

function ImageUploader() {
  const [images, setImages] = useState([]);
  const [uploadImage, result] = useUploadImageMutation();

  const onDrop = useCallback(acceptedFiles => {
    filesUpload(acceptedFiles).then(imagesResponse => {
      setImages(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 => {
      return Promise.resolve(response.data);
    });
  }

  const filesUpload = (files) => {
    return Promise.all(files.map(fileUpload));
  }

  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'}}>
        {images && images.map(image =>
          <Box sx={{ width: '60px' }}>
            <Image key={image?._id} url={image?.url} />
          </Box>
        )}
      </Box>
    </>
  )
}

export default ImageUploader;