import React, { useMemo, useState } from 'react';
import { useDropzone } from 'react-dropzone';
import { Box } from '@mui/material';
import Dnd from './DnD';
import { useSetUploadImageMutation } from '../store/ImgUploadApi';

function Image({ url, click }) {

  return (
    <img className="good-image" src={`http://shop-roles.node.ed.asmer.org.ua/${url}`} onClick={click} style={{
      width: "100%",
      height: "100%",
      objectFit: "contain",
    }}/>
  )
}

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 = Function.prototype }) { // onChange функция из пропсов запускаемая при обновлении массива картинок.
  const [images, setImages] = useState(passImages || []); //passImages массив картинок из пропсов, 
  const [uploadImage, result] = useSetUploadImageMutation(); //   uploadImage функция мутации (отправки данных на сервер)
  console.log('result', result);

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

  const updateImages = images => {
    console.log('images', images)
    setImages(images);
    onChange(images);
  }

  const onDrop = acceptedFiles => {
    console.log('дропнуло', acceptedFiles)

     filesUpload(acceptedFiles).then(imagesResponse => {
       updateImages(images.concat(imagesResponse));
     });
  }

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

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

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