import { toast } from "react-toastify";
import { useDropzone } from "react-dropzone";
import "./assets/css/styles.css";
import { Dispatch, SetStateAction } from "react";
import "react-toastify/dist/ReactToastify.css";

// Define the props interface for the ImageDropzone component.
interface props {
  setImage: Dispatch<SetStateAction<File | null>>;
  preview: string | ArrayBuffer | null;
  setPreview: Dispatch<SetStateAction<string | ArrayBuffer | null>>;
}

// ImageDropzone component allows users to drag and drop an image or select it via a file input.
export const ImageDropzone = ({ setImage, preview, setPreview }: props) => {
  // Define the maximum file size for the dropzone (10 MB).
  const MAX_SIZE = 10485760;

  // Configure the dropzone with the necessary options and event handlers.
  const { getRootProps, getInputProps } = useDropzone({
    multiple: false,
    maxSize: MAX_SIZE,
    accept: {
      "image/jpeg": [],
      "image/png": [],
    },
    onDrop(acceptedFiles, fileRejections) {
      // Handle file rejections (e.g., file too large, incorrect file type) by showing a toast notification.
      fileRejections.map(({ file, errors }) =>
        toast.error(errors[0].message, {
          position: "bottom-right",
          autoClose: 1500,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: false,
          draggable: true,
          progress: undefined,
          theme: "colored",
        })
      );

      // Handle accepted files by setting the image and preview state.
      acceptedFiles.forEach((file) => {
        const preview = URL.createObjectURL(file);
        setImage(file);
        setPreview(preview);
      });
    },
  });

  return (
    // Render the dropzone container.
    <div className="image_dropzone_container">
      <div {...getRootProps({ className: "image_dropzone" })}>
        <input {...getInputProps()} />
        {preview ? (
          // If a preview is available, show the image preview.
          <img
            src={preview as string}
            title="Arrastra tu imagen o seleccionala dando click aquí"
            alt=""
          ></img>
        ) : (
          // If no preview is available, show a placeholder text.
          <p>Arrastra tu imagen o seleccionala dando click aquí.</p>
        )}
      </div>
    </div>
  );
};
