import React, { useState } from "react";
import { useDropzone } from "react-dropzone";
import { Box, Button } from "@mui/material";
import { actionUploadPhoto } from "../../actions";
import { connect } from "react-redux";

const UploadForm = ({ onUpload, state }) => {
  const [file, setFile] = useState(null);

  const { acceptedFiles, getRootProps, getInputProps } = useDropzone({
    accept: "image/*",
    multiple: false,
    onDrop: (acceptedFiles) => {
      setFile(acceptedFiles[0]);
    },
  });

  let userId = state?.auth.payload?.id;

  const isButtonDisabled = !file;

  return (
    <Box className="photo-input">
      <Box
        sx={{
          border: "2px dashed gray",
          borderRadius: "50%",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
          width: "fit-content",
          height: "fit-content",
          padding: "20px",
          cursor: "pointer",
        }}
        {...getRootProps({ className: "dropzone" })}
      >
        <input {...getInputProps()} />
        {file ? (
          <Box component="img" src={URL.createObjectURL(file)} alt="img-icon" />
        ) : (
          <Box component="img" src="https://cdn-icons-png.flaticon.com/512/1829/1829415.png" alt="img-icon" />
        )}
      </Box>
      {file ? (
        <Button disabled={isButtonDisabled} onClick={() => onUpload(file, userId)}>
          Запостить
        </Button>
      ) : (
        <Box sx={{color: "red", textAlign: "center", marginBottom: "12px"}}>Выберите фото</Box>
      )}
    </Box>
  );
};

export const ConnectUploadPhotoForm = connect(
  (state) => ({ state: state }),
  { onUpload: actionUploadPhoto }
)(UploadForm);
