"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,
  deleteGaleryFile,
} from "@/service/galery";
import { error, success } from "@/config/swal";
import withReactContent from "sweetalert2-react-content";
import Swal from "sweetalert2";

export function DialogUpdateGaleri({ open, onClose, data, onUpdated }: any) {
  const [title, setTitle] = useState("");
  const MySwal = withReactContent(Swal);
  const [description, setDescription] = useState("");
  const [oldFiles, setOldFiles] = useState<any[]>([]);
  const [newFiles, setNewFiles] = useState<File[]>([]);
  const [newFilePreviews, setNewFilePreviews] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);

  const fetchOldFiles = async (galleryId: any) => {
    try {
      const res = await getGaleryFileData(galleryId);
      const allImages = res?.data?.data ?? [];
      const filtered = allImages.filter(
        (img: any) => img.gallery_id === galleryId
      );
      setOldFiles(filtered);
    } catch (e) {
      console.error("Error fetching files:", e);
    }
  };

  useEffect(() => {
    if (open && data?.id) {
      setTitle(data.title ?? "");

      setDescription(data.description ?? data.desc ?? "");
      fetchOldFiles(data.id);

      setNewFiles([]);
      setNewFilePreviews([]);
    } else if (!open) {
    }
  }, [open, data]);

  useEffect(() => {
    if (!newFiles || newFiles.length === 0) {
      setNewFilePreviews([]);
      return;
    }

    const urls = newFiles.map((f) => URL.createObjectURL(f));
    setNewFilePreviews(urls);

    return () => {
      urls.forEach((u) => URL.revokeObjectURL(u));
    };
  }, [newFiles]);

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

  async function doDelete(id: any) {
    const resDelete = await deleteGaleryFile(id);
    if (resDelete?.error) {
      error(resDelete.message);
      return false;
    }
    success("Berhasil Hapus");
    return;
  }

  const removeOldFile = (id: any) => {
    MySwal.fire({
      title: "Hapus Data",
      icon: "warning",
      showCancelButton: true,
      cancelButtonColor: "#3085d6",
      confirmButtonColor: "#d33",
      confirmButtonText: "Hapus",
    }).then((result) => {
      if (result.isConfirmed) {
        doDelete(id);
      }
    });
  };

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

  const handleSubmit = async () => {
    try {
      if (!data?.id) {
        alert("Gallery ID tidak tersedia.");
        return;
      }

      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)));

      const updateRes = await updateGalery(data.id, formMain);
      console.log("updateGalery response:", updateRes);

      if (updateRes?.error) {
        alert(updateRes.message || "Gagal update galeri");
        setLoading(false);
        return;
      }

      const galleryId = data.id;
      const failedUploads: any[] = [];

      for (const file of newFiles) {
        try {
          const formFile = new FormData();
          formFile.append("gallery_id", String(galleryId));
          formFile.append("title", title);
          formFile.append("is_active", "true");
          formFile.append("file", file);

          const uploadRes = await updateUploadGaleryFile(data.id, formFile);

          console.log("uploadRes:", uploadRes);

          if (uploadRes?.error) {
            failedUploads.push({
              name: file.name,
              error: uploadRes.message,
            });
          }
        } catch (err: any) {
          failedUploads.push({ name: file.name, error: err });
        }
      }

      setLoading(false);

      if (failedUploads.length > 0) {
        let msg = failedUploads.map((f) => `${f.name}: ${f.error}`).join("\n");
        alert("Ada file gagal diupload:\n" + msg);
        return;
      }

      onClose();
      onUpdated && onUpdated();
    } catch (err: any) {
      setLoading(false);
      console.error("Update error:", err);

      if (err?.response?.data) {
        alert("Server error: " + JSON.stringify(err.response.data));
      } else {
        alert("Gagal menyimpan galeri");
      }
    }
  };

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

        <div className="space-y-4 px-4 pb-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>

            {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 || "image"}
                      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>
            )}

            {newFilePreviews.length > 0 && (
              <div className="flex gap-3 mt-3 flex-wrap">
                {newFilePreviews.map((src, idx) => (
                  <div
                    key={idx}
                    className="relative w-20 h-20 overflow-hidden rounded-lg border"
                  >
                    <img
                      src={src}
                      alt={`new-${idx}`}
                      className="object-cover w-full h-full"
                    />
                    <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>

        <DialogFooter className="mt-6 flex gap-2 px-4 pb-4">
          <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>
  );
}
