import React, { useState, useEffect } from "react";
import { useDropzone } from "react-dropzone";
import { actionUploadPost } from "../../actions";
import { useHistory } from "react-router-dom";
import { connect } from "react-redux";
import { Box, Button, TextField } from "@mui/material";
import { PostInput, PostInputForm } from "./upload-form.module";
//
// const reorder = (list, startIndex, endIndex) => {
//     if (startIndex > endIndex) {
//     [startIndex, endIndex] = [endIndex, startIndex];
//   }
//   const result = Array.from(list);
//   const [removed] = result.splice(startIndex, 1);
//   result.splice(endIndex, 0, removed);
//
//   return result;
// };
//
// const UploadForm = ({ onUpload, isUpload }) => {
//
//   const [acceptedFiles, setAcceptedFiles] = useState([]);
//   const { getRootProps, getInputProps } = useDropzone({
//     onDrop: (acceptedFiles) => {
//       setAcceptedFiles(acceptedFiles);
//     },
//   });
//   const [title, setTitle] = useState("");
//   const [text, setText] = useState("");
//   const [currentDragItem, setCurrentDragItem] = useState();
//
//   const history = useHistory();
//   isUpload && history.push("/");
//
//   const drag = (event) => {
//     setCurrentDragItem(event.target);
//   };
//
//   function allowDrop(event) {
//     event.preventDefault();
//   }
//
//   function drop(event) {
//     const items = reorder(acceptedFiles, currentDragItem.id, event.target.id);
//
//     setAcceptedFiles(items);
//   }
//
//   return (
//     <PostInput className="post-input">
//       <Box {...getRootProps({ className: "dropzone" })}>
//         <input {...getInputProps()} multiple />
//         <Box
//           component="img"
//           src="https://cdn-icons-png.flaticon.com/512/1829/1829415.png"
//           alt="img-icon"
//         />
//         <Box component="p">Переместите изображение для загрузки</Box>
//       </Box>
//       <Box
//         style={{
//           textAlign: "center",
//           border: "1px solid black",
//           width: "50%",
//           minHeight: "100px",
//           margin: "10px auto",
//         }}
//         onDrop={(event) => drop(event)}
//         onDragOver={(event) => allowDrop(event)}
//       >
//         {acceptedFiles.map((file, index) => (
//           <Box
//             key={index}
//             id={index}
//             component="img"
//             src={URL.createObjectURL(file)}
//             alt="preview"
//             draggable="true"
//             onDragStart={drag}
//             style={{
//               width: 100,
//               height: 100,
//               marginRight: 10,
//               objectFit: "cover",
//             }}
//           />
//         ))}
//       </Box>
//       <PostInputForm className="post-input-form">
//         <TextField
//           type="text"
//           placeholder="Title"
//           value={title}
//           onChange={(e) => setTitle(e.target.value)}
//         />
//         <TextField
//           type="text"
//           placeholder="Text"
//           value={text}
//           onChange={(e) => setText(e.target.value)}
//         />
//         <Button onClick={() => onUpload(text, title, acceptedFiles[0])}>
//           Запостить
//         </Button>
//       </PostInputForm>
//     </PostInput>
//   );
// };
//
// export const ConnectUploadForm = connect(
//   (state) => ({isUpload: state?.promise?.InsertPosts?.payload?.data?.PostUpsert,}),
//   { onUpload: actionUploadPost }
// )(UploadForm);

const reorder = (list, startIndex, endIndex) => {
    if (startIndex > endIndex) {
        [startIndex, endIndex] = [endIndex, startIndex];
    }

    const result = Array.from(list);
    const [removed] = result.splice(startIndex, 1);
    result.splice(endIndex, 0, removed);

    return result;
};

const UploadForm = ({ onUpload, isUpload }) => {
    const [acceptedFiles, setAcceptedFiles] = useState([]);
    const [title, setTitle] = useState("");
    const [text, setText] = useState("");
    const [currentDragItem, setCurrentDragItem] = useState();

    const history = useHistory();
    useEffect(() => {
        if (isUpload) {
            history.push("/");
        }
    }, [isUpload, history]);

    const { getRootProps, getInputProps } = useDropzone({
        onDrop: (acceptedFiles) => {
            setAcceptedFiles(acceptedFiles);
        },
    });

    const handleDragStart = (event, index) => {
        setCurrentDragItem(index);
    };

    const handleDragOver = (event) => {
        event.preventDefault();
    };

    const handleDrop = (event, index) => {
        const items = reorder(acceptedFiles, currentDragItem, index);
        setAcceptedFiles(items);
    };

    return (
        <PostInput className="post-input">
            <Box {...getRootProps({ className: "dropzone" })}>
                <input {...getInputProps()} multiple />
                <Box
                    component="img"
                    src="https://cdn-icons-png.flaticon.com/512/1829/1829415.png"
                    alt="img-icon"
                />
                <Box component="p">Переместите изображение для загрузки</Box>
            </Box>
            <Box
                style={{
                    textAlign: "center",
                    border: "1px solid black",
                    width: "50%",
                    minHeight: "100px",
                    margin: "10px auto",
                }}
                onDragOver={handleDragOver}
                onDrop={handleDrop}
            >
                {acceptedFiles.map((file, index) => (
                    <Box
                        key={index}
                        id={index}
                        component="img"
                        src={URL.createObjectURL(file)}
                        alt="preview"
                        draggable="true"
                        onDragStart={(event) => handleDragStart(event, index)}
                        style={{
                            width: 100,
                            height: 100,
                            marginRight: 10,
                            objectFit: "cover",
                        }}
                    />
                ))}
            </Box>
            <PostInputForm className="post-input-form">
                <TextField
                    type="text"
                    placeholder="Title"
                    value={title}
                    onChange={(e) => setTitle(e.target.value)}
                />
                <TextField
                    type="text"
                    placeholder="Text"
                    value={text}
                    onChange={(e) => setText(e.target.value)}
                />
                <Button onClick={() => onUpload(text, title, acceptedFiles[0])}>
                    Запостить
                </Button>
            </PostInputForm>
        </PostInput>
    );
};

export const ConnectUploadForm = connect(
    (state) => ({
        isUpload: state?.promise?.InsertPosts?.payload?.data?.PostUpsert,
    }),
    { onUpload: actionUploadPost }
)(UploadForm);
