"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { X } from "lucide-react";
import {
  getGaleryFileData,
  updateGalery,
  updateUploadGaleryFile,
} from "@/service/galery";

export function DialogUpdateGaleri({ open, onClose, data, onUpdated }: any) {
  const [title, setTitle] = useState(data.title || "");
  const [description, setDescription] = useState(data.desc || "");
  const [oldFiles, setOldFiles] = useState<any[]>([]);
  const [newFiles, setNewFiles] = useState<File[]>([]);
  const [loading, setLoading] = useState(false);

  const fetchOldFiles = async () => {
    try {
      const res = await getGaleryFileData(data.id);
      const allImages = res?.data?.data ?? [];

      const filteredImages = allImages.filter(
        (img: any) => img.gallery_id === data.id
      );

      setOldFiles(filteredImages);
    } catch (e) {
      console.error("Error fetch files:", e);
    }
  };

  useEffect(() => {
    if (open && data?.id) {
      fetchOldFiles();
      setTitle(data.title || "");
      setDescription(data.description || "");
    }
  }, [open, data]);

  const handleUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const uploaded = Array.from(e.target.files || []) as File[];
    setNewFiles((prev) => [...prev, ...uploaded]);
  };

  const removeOldFile = (id: number) => {
    setOldFiles((prev) => prev.filter((f) => f.id !== id));
  };

  const removeNewFile = (index: number) => {
    setNewFiles((prev) => prev.filter((_, i) => i !== index));
  };

  const handleSubmit = async () => {
    try {
      setLoading(true);

      const formMain = new FormData();
      formMain.append("title", title);
      formMain.append("description", description);

      formMain.append("old_files", JSON.stringify(oldFiles.map((f) => f.id)));

      await updateGalery(data.id, formMain);

      for (const file of newFiles) {
        const formFile = new FormData();
        formFile.append("gallery_id", String(data.id));
        formFile.append("title", title);
        formFile.append("file", file);

        await updateUploadGaleryFile(data.id, formFile);
      }

      setLoading(false);
      onClose();
      if (onUpdated) onUpdated();
    } catch (err) {
      setLoading(false);
      console.error("Error update gallery:", err);
      alert("Gagal menyimpan perubahan galeri");
    }
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-xl rounded-2xl">
        <DialogHeader>
          <DialogTitle>Edit Galeri</DialogTitle>
        </DialogHeader>

        {/* FORM */}
        <div className="space-y-4">
          {/* TITLE */}
          <div>
            <label className="font-medium text-sm">Judul Galeri *</label>
            <input
              className="w-full border rounded-lg px-3 py-2 mt-1"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
            />
          </div>

          {/* DESCRIPTION */}
          <div>
            <label className="font-medium text-sm">Deskripsi Galeri *</label>
            <textarea
              className="w-full border rounded-lg px-3 py-2 mt-1"
              rows={3}
              value={description}
              onChange={(e) => setDescription(e.target.value)}
            />
          </div>

          {/* UPLOAD FILE */}
          <div>
            <label className="font-medium text-sm">Upload File</label>
            <label className="mt-2 flex flex-col items-center justify-center border border-dashed rounded-xl py-6 cursor-pointer">
              <input
                type="file"
                className="hidden"
                multiple
                onChange={handleUpload}
              />
              <div className="flex flex-col items-center text-gray-500">
                <svg width="32" height="32" fill="#1F6779">
                  <path d="M5 20h14v-2H5v2zm7-16l-5 5h3v4h4v-4h3l-5-5z" />
                </svg>
                <p>Klik untuk upload atau drag & drop</p>
                <p className="text-xs">PNG, JPG (max 2MB)</p>
              </div>
            </label>

            {/* OLD FILES */}
            {oldFiles.length > 0 && (
              <div className="flex gap-3 mt-3 flex-wrap">
                {oldFiles.map((f) => (
                  <div key={f.id} className="relative w-20 h-20">
                    <Image
                      src={f.image_url}
                      alt={f.title}
                      fill
                      className="object-cover rounded-lg"
                    />
                    <button
                      onClick={() => removeOldFile(f.id)}
                      className="absolute -top-2 -right-2 bg-red-600 text-white rounded-full p-1"
                    >
                      <X size={12} />
                    </button>
                  </div>
                ))}
              </div>
            )}

            {/* NEW FILES */}
            {newFiles.length > 0 && (
              <div className="flex gap-3 mt-3 flex-wrap">
                {newFiles.map((file, idx) => (
                  <div key={idx} className="relative w-20 h-20">
                    <Image
                      src={URL.createObjectURL(file)}
                      alt={file.name}
                      fill
                      className="object-cover rounded-lg"
                    />
                    <button
                      onClick={() => removeNewFile(idx)}
                      className="absolute -top-2 -right-2 bg-red-600 text-white rounded-full p-1"
                    >
                      <X size={12} />
                    </button>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* FOOTER */}
        <DialogFooter className="mt-6 flex gap-2">
          <button
            onClick={onClose}
            className="px-6 py-2 rounded-lg bg-gray-200 text-gray-700"
          >
            Batal
          </button>

          <button
            disabled={loading}
            onClick={handleSubmit}
            className="px-6 py-2 rounded-lg bg-[#1F6779] text-white"
          >
            {loading ? "Menyimpan..." : "Simpan"}
          </button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
