"use client";

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

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

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

  const removeOldFile = (id: number) => {
    setFiles(files.filter((f: any) => f.id !== id));
  };

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

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

      const form = new FormData();
      form.append("title", title);
      form.append("desc", desc);

      // file lama yang masih dipakai
      form.append("old_files", JSON.stringify(files.map((f: any) => f.id)));

      // file baru
      newFiles.forEach((file) => {
        form.append("files", file);
      });

      const res = await updateGalery(data.id, form);

      setLoading(false);
      onClose();
      if (onUpdated) onUpdated(); // refresh list
    } catch (error) {
      setLoading(false);
      console.error("Error update:", error);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-xl rounded-2xl">
        <DialogHeader className="mb-4">
          <DialogTitle>Edit Banner</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)}
              required
            />
          </div>

          {/* Desc */}
          <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={desc}
              onChange={(e) => setDesc(e.target.value)}
            />
          </div>

          {/* Upload */}
          <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>

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

            {/* NEW FILES */}
            <div className="flex gap-3 mt-3">
              {newFiles.map((file, idx) => (
                <div key={idx} className="relative w-20 h-20">
                  <Image
                    src={URL.createObjectURL(file)}
                    alt=""
                    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">
          <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>
  );
}
