"use client";

import { useState, useRef, useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useRouter } from "next/navigation";
import axios from "axios";
import Image from "next/image";
import { createCollectionSchema } from "@/lib/zodSchemas";
import DeleteConfirmationModal from "@/components/admin/custom ui/ImageDeleteMOdal";
import ToastMessage from "@/components/common/ToastMessage";
import { FaImage } from "react-icons/fa6";

interface CollectionFormProps {
  initialData?: CollectionType | null;
}

const CollectionForm: React.FC<CollectionFormProps> = ({ initialData }) => {
  const [loading, setLoading] = useState(false);
  const router = useRouter();
  const [imageFiles, setImageFiles] = useState<File[]>([]);
  const [previewImages, setPreviewImages] = useState<string[]>([]);
  const [uploadedImageURLs, setUploadedImageURLs] = useState<Object[]>([]);
  const [deleteImages, setDeleteImages] = useState<string[]>([]);
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const [confirmationModal, setConfirmationModal] = useState({
    show: false,
    url: null as string | null,
  });

  useEffect(() => {
    if (initialData) {
      setUploadedImageURLs(initialData.collection_images);
    } else {
      setUploadedImageURLs([]);
    }
  }, [initialData]);

  const form = useForm<z.infer<typeof createCollectionSchema>>({
    resolver: zodResolver(createCollectionSchema),
    defaultValues: initialData || {
      title: "",
      description: "",
      collection_images: [],
    },
  });

  const handleKeyPress = (
    e:
      | React.KeyboardEvent<HTMLInputElement>
      | React.KeyboardEvent<HTMLTextAreaElement>
  ) => {
    if (e.key === "Enter") {
      e.preventDefault();
    }
  };

  const onSubmit = async (values: z.infer<typeof createCollectionSchema>) => {
    setLoading(true);
    const apiUrl = initialData
      ? `/api/admin/collections/${initialData.uuid}`
      : "/api/admin/collections";

    try {
      if (imageFiles.length === 0 && uploadedImageURLs.length === 0) {
        setLoading(false);
        ToastMessage("At least one image must be uploaded", "error");
        return;
      }

      const formData = new FormData();
      formData.append("title", values.title);
      formData.append("description", values.description);
      formData.append("imagesCount", imageFiles.length.toString());
      formData.append("deleteImageCount", deleteImages.length.toString());

      imageFiles.forEach((file, index) => {
        formData.append(`image_${index}`, file);
      });

      deleteImages.forEach((imgId, index) => {
        formData.append(`deleteImageId_${index}`, imgId);
      });

      const response = initialData
        ? await axios.put(apiUrl, formData)
        : await axios.post(apiUrl, formData);

      if (response.status === 200) {
        ToastMessage(
          initialData
            ? "Collection updated successfully"
            : "Collection created successfully",
          "success"
        );
        setLoading(false);
        router.push("/admin/collections");
      }
    } catch (error: any) {
      ToastMessage(error.message, "error");
    } finally {
      setLoading(false);
    }
  };

  const handleImageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files) {
      const files = Array.from(event.target.files);
      setImageFiles((prev) => [...prev, ...files]);
      form.setValue("collection_images", [...imageFiles, ...files]);

      const previewURLs = files.map((file) => URL.createObjectURL(file));
      setPreviewImages((prev) => [...prev, ...previewURLs]);
    }
  };

  const handleRemoveImage = (index: number) => {
    const newFiles = [...imageFiles];
    const newPreviews = [...previewImages];
    newFiles.splice(index, 1);
    newPreviews.splice(index, 1);
    setImageFiles(newFiles);
    setPreviewImages(newPreviews);
    form.setValue("collection_images", newFiles);
  };

  const prevImagesRemove = (url: string) => {
    setUploadedImageURLs((prev) =>
      prev.filter((imageObj: any) => imageObj.uuid !== url)
    );
    setDeleteImages((prev) => [...prev, url]);
    setConfirmationModal({ show: false, url: null });
  };

  const handleDeleteClick = (imgObj: any) => {
    const url = imgObj?.uuid;
    setConfirmationModal({ show: true, url });
  };

  const handleCloseModal = () => {
    setConfirmationModal({ show: false, url: null });
  };

  return (
    <div className="space-y-4 p-4">
      <h2 className="text-2xl font-bold">
        {initialData ? "Edit Collection" : "Add New Collection"}
      </h2>

      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
        <div>
          <label className="block mb-2 text-lg font-medium">Name</label>
          <input
            type="text"
            {...form.register("title")}
            onKeyDown={handleKeyPress}
            className="w-full border border-gray-300 rounded-md p-2"
            placeholder="Collection name"
          />
        </div>

        <div>
          <label className="block mb-2 text-lg font-medium">Description</label>
          <textarea
            {...form.register("description")}
            onKeyDown={handleKeyPress}
            className="w-full border border-gray-300 rounded-md p-2"
            placeholder="Collection details"
          ></textarea>
        </div>

        <div>
          <label className="block mb-2 text-lg font-medium">Image</label>
          <div className="flex flex-col items-center border-2 border-dashed border-gray-300 p-6 rounded-md">
            <FaImage className="text-gray-500 text-4xl" />
            <label className="mt-4 cursor-pointer text-blue-600 font-semibold">
              Upload a file
              <input
                type="file"
                className="hidden"
                onChange={handleImageChange}
                multiple
              />
            </label>
            <p className="text-sm text-gray-500 mt-2">or drag and drop</p>
            <p className="text-xs text-gray-400">PNG, JPG, GIF up to 5MB</p>
          </div>

          {previewImages.length > 0 && (
            <div className="mt-4">
              <label className="block text-md font-medium mb-2">
                Selected Images:
              </label>
              <div className="flex gap-4 flex-wrap">
                {previewImages.map((src, index) => (
                  <div key={index} className="relative w-[180px] h-[180px]">
                    <button
                      type="button"
                      onClick={() => handleRemoveImage(index)}
                      className="absolute top-0 right-0 bg-white border border-gray-200 rounded-full p-1 z-10"
                    >
                      <span className="text-red-500 font-bold">X</span>
                    </button>
                    <Image
                      src={src}
                      alt={`Preview ${index}`}
                      fill
                      className="object-cover rounded-md"
                    />
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        <div className="flex gap-4">
          {!initialData && (
            <button
              type="button"
              onClick={() => router.back()}
              className="px-6 py-2 border border-gray-300 rounded-md hover:bg-gray-100"
            >
              Cancel
            </button>
          )}
          <button
            type="submit"
            disabled={loading}
            className="px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
          >
            {loading
              ? "Loading..."
              : initialData
              ? "Update Collection"
              : "Add Collection"}
          </button>
        </div>
      </form>

      <DeleteConfirmationModal
        show={confirmationModal.show}
        onConfirm={() => prevImagesRemove(confirmationModal.url!)}
        onCancel={handleCloseModal}
        message="Are you sure you want to delete this image?"
      />
    </div>
  );
};

export default CollectionForm;
