// Import necessary modules and hooks from libraries
import { useEffect, useState } from "react";
import { useDropzone } from "react-dropzone";
import { toast } from "react-toastify";
import { Image } from "../../data/datasource/api/entities/image";
import { UseFormSetValue } from "react-hook-form";
import { Place } from "../../data/datasource/api/entities/place";

// Custom hook for handling multiple image uploads using dropzone
export const useDropzoneMultiplesImages = (
  setValue: UseFormSetValue<Place>,
  imagesList?: File[] | string[]
) => {
  const [imagesFiles, setImagesFiles] = useState<Image[]>([]);
  const [files, setFiles] = useState<File[]>([]);
  const MAX_SIZE = 10485760; // Maximum file size (10MB)
  const { getRootProps, getInputProps } = useDropzone({
    maxSize: MAX_SIZE,
    accept: {
      "image/*": [],
    },
    onDrop(acceptedFiles, fileRejections) {
      // Handle file rejections
      fileRejections.map(({ file, errors }) =>
        toast.error("Error: " + errors[0].message + " : " + file.name, {
          position: "bottom-right",
          autoClose: 1500,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: false,
          draggable: true,
          progress: undefined,
          theme: "colored",
        })
      );

      const backupImages = [...imagesFiles];
      const backupFiles = [...files];
      acceptedFiles.forEach((file, index) => {
        if (imagesFiles.length <= 10 && index < 10) {
          const preview = URL.createObjectURL(file);
          backupImages.push({ file, preview });
          backupFiles.push(file);
        } else {
          toast.error("Error: Ha superado los 10 archivos", {
            position: "bottom-right",
            autoClose: 1500,
            hideProgressBar: false,
            closeOnClick: true,
            pauseOnHover: false,
            draggable: true,
            progress: undefined,
            theme: "colored",
          });
        }
      });
      setImagesFiles(backupImages);
      setFiles(backupFiles);
      setValue("imagesList", backupFiles, { shouldValidate: true });
    },
  });

  // Function to remove an image by index
  const removeImage = (index: number) => {
    const backupImages = [...imagesFiles];
    const backupFiles = [...files];
    backupImages.splice(index, 1);
    backupFiles.splice(index, 1);
    setImagesFiles(backupImages);
    setFiles(backupFiles);
    setValue("imagesList", backupFiles, { shouldValidate: true });
  };

  // Effect to process initial images list
  useEffect(() => {
    if (imagesList && imagesList.length > 0) {
      const backupImages: Image[] = [];
      const backupFiles: File[] = [];
      const processImages = async () => {
        const promises = imagesList.map(async (imageURL) => {
          if (typeof imageURL === "string") {
            const response = await fetch(imageURL);
            const blob = await response.blob();
            const file = new File([blob], "image.jpg", { type: blob.type });
            backupImages.push({ file, preview: imageURL });
            backupFiles.push(file);
          }
        });
        await Promise.all(promises);
      };

      processImages().then(() => {
        setImagesFiles(backupImages);
        setFiles(backupFiles);
        setValue("imagesList", backupFiles);
      });
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [imagesList]);

  return { getInputProps, getRootProps, imagesFiles, removeImage };
};
