/* eslint-disable @typescript-eslint/no-explicit-any */
import { IMAGE_BASE_URL, buildStorageUrl } from "@/components/main/BaseUrl";
import { useState } from "react";

type ImageUploaderProps = {
  formik: any;
};

const ImageUploader: React.FC<ImageUploaderProps> = ({ formik }) => {
  const [images, setImages] = useState<string[]>(formik.values.images || []);

  const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (!event.target.files) return;
    const files = Array.from(event.target.files);

    if (images.length + files.length > 5) {
      alert("حداکثر ۵ عکس می‌توانید انتخاب کنید");
      return;
    }

    const newImages: string[] = [];

    files.forEach((file) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        if (typeof reader.result === "string") {
          newImages.push(reader.result);
          if (newImages.length === files.length) {
            const updatedImages = [...images, ...newImages];
            setImages(updatedImages);
            formik.setFieldValue("images", updatedImages);
          }
        }
      };
    });
  };

  const handleRemoveImage = (index: number) => {
    const newImages = images.filter((_, i) => i !== index);
    setImages(newImages);
    formik.setFieldValue("images", newImages);
  };

  return (
    <div className="flex flex-wrap gap-2 w-full mt-5">
      {images.map((image, index) => (
        <div
          key={crypto.randomUUID()}
          className="relative w-24 h-24 rounded-lg overflow-hidden border"
        >
          <img
            src={
              images[index].slice(0, 12) === "/advertising"
                ? IMAGE_BASE_URL + image
                : image
            }
            alt="uploaded"
            className="w-full h-full object-cover"
          />
          <button
            type="button"
            className="absolute top-1 right-1 bg-black bg-opacity-50 p-1 px-2.5 rounded-full text-white"
            onClick={() => handleRemoveImage(index)}
          >
            x
          </button>
        </div>
      ))}
      {images.length < 5 && (
        <label className="w-24 h-24 flex items-center justify-center border-dashed border-2 cursor-pointer rounded-lg">
          <input
            type="file"
            multiple
            accept="image/*"
            className="hidden"
            onChange={handleImageUpload}
          />
          +
        </label>
      )}
    </div>
  );
};

export default ImageUploader;
