"use client";

import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import Image from "next/image";
import { Check, CheckCheck, CheckCircle, Clock, X } from "lucide-react";
import { useEffect, useState } from "react";
import { approveGalery, getGaleryFileData } from "@/service/galery";
import { convertDateFormat } from "@/utils/global";
import { Button } from "../ui/button";
import { useRouter } from "next/navigation";
import Cookies from "js-cookie";
import { error, loading, success } from "@/config/swal";

export function DialogDetailGaleri({ open, onClose, data }: any) {
  const [images, setImages] = useState<any[]>([]);
  const [openApproverHistory, setOpenApproverHistory] = useState(false);
  const [userLevelId, setUserLevelId] = useState<string | null>(null);
  const [openViewDialog, setOpenViewDialog] = useState(false);
  const router = useRouter();

  // 🔹 Ambil userlevelId dari cookies
  useEffect(() => {
    const ulne = Cookies.get("ulne"); // contoh: "3"
    setUserLevelId(ulne ?? null);
  }, []);

  const [openCommentModal, setOpenCommentModal] = useState(false);
  const [commentValue, setCommentValue] = useState("");

  const handleSubmitComment = async () => {
    // await api.post("/banner/comment", {
    //   bannerId: viewBanner.id,
    //   comment: commentValue,
    // });

    setOpenCommentModal(false);
  };
  const fetchImages = async () => {
    try {
      const res = await getGaleryFileData(data.id);
      const allImages = res?.data?.data ?? [];

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

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

  useEffect(() => {
    if (open && data?.id) {
      fetchImages();
    }
  }, [open, data]);

  const openFile = (url: string) => {
    window.open(url, "_blank");
  };
  const handleOpenApproverHistory = () => {
    setOpenApproverHistory(true);
  };

  const handleApproveGalery = async (id: number) => {
    loading();
    const res = await approveGalery(id);

    if (res?.error) {
      error(res.message || "Gagal menyetujui galeri");
      close();
      return;
    }

    close();
    success("Galeri berhasil disetujui");
    fetchImages(); // refresh table
  };

  return (
    <>
      <Dialog open={open} onOpenChange={onClose}>
        <DialogContent className="max-w-3xl rounded-2xl p-0 overflow-hidden">
          {/* Header */}
          <div className="bg-[#1F6779] text-white px-6 py-4">
            <DialogTitle className="text-white">Detail Galeri</DialogTitle>
          </div>

          <div className="px-6 py-3">
            {/* Images List */}
            <div>
              <h2 className="text-2xl font-semibold text-black">
                {data.title}
              </h2>
              <div className="my-3">
                <p className="font-medium text-sm text-black">Deskripsi</p>
                <p className="text-gray-800">{data.description}</p>
              </div>
              <div className="grid grid-cols-3 gap-4">
                {images.length === 0 && (
                  <p className="text-gray-500 col-span-3 text-center">
                    Tidak ada gambar.
                  </p>
                )}

                {images.map((img) => (
                  <div
                    key={img.id}
                    className="relative h-32 w-full cursor-pointer group"
                    onClick={() => openFile(img.image_url)}
                  >
                    <Image
                      src={img.image_url}
                      alt={img.title}
                      fill
                      className="object-cover rounded-lg"
                    />

                    <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 text-white flex items-center justify-center text-sm transition">
                      Lihat File
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* Title */}

            {/* Deskripsi */}

            {/* Tanggal Upload */}
            <div>
              <p className="font-medium text-sm text-gray-700">
                Tanggal Upload
              </p>
              <p className="text-gray-600">
                {new Date(data.created_at).toLocaleDateString("id-ID")}
              </p>
            </div>

            {/* Timeline */}
            <div>
              <h4 className="text-sm font-semibold text-gray-700 mb-3">
                Status Timeline
              </h4>

              <div className="space-y-4">
                <div className="flex gap-3">
                  <div className="w-6 h-6 rounded-full bg-green-100 flex items-center justify-center">
                    <Check className="w-4 h-4 text-green-600" />
                  </div>
                  <div>
                    <p className="font-medium text-gray-800">
                      Diupload oleh Operator
                    </p>
                    <p className="text-sm text-gray-500">
                      {convertDateFormat(data?.created_at)} WIB
                    </p>
                  </div>
                </div>

                <div className="flex gap-3">
                  <div
                    className={`w-6 h-6 rounded-full flex items-center justify-center ${
                      data?.status_id === 1
                        ? "bg-yellow-100"
                        : data?.status_id === 2
                          ? "bg-green-100"
                          : "bg-red-100"
                    }`}
                  >
                    {data?.status_id === 1 ? (
                      <Clock className="w-4 h-4 text-yellow-700" />
                    ) : data?.status_id === 2 ? (
                      <Check className="w-4 h-4 text-green-600" />
                    ) : (
                      <X className="w-4 h-4 text-red-700" />
                    )}
                  </div>

                  <div>
                    <p className="font-medium text-gray-800">
                      {data?.status_id === 1
                        ? "Menunggu disetujui oleh Approver"
                        : data?.status_id === 2
                          ? "Disetujui oleh Approver"
                          : "Ditolak oleh Approver"}
                    </p>

                    <p className="text-sm text-gray-500">
                      {convertDateFormat(data?.updated_at)} WIB
                    </p>
                  </div>
                </div>

                <div className="border rounded-lg px-3 py-3">
                  <p>Comment : </p>
                  <div className="flex flex-row justify-between">
                    <button
                      onClick={handleOpenApproverHistory}
                      className="text-sm text-blue-600 hover:underline mt-2"
                    >
                      View Approver History
                    </button>
                    <p>Jaecoo - Approver | 10/11/2026</p>
                  </div>
                </div>
              </div>
            </div>
            {openViewDialog && userLevelId !== "2" && (
              <div className="flex justify-between items-center gap-3 px-6 py-4 border-t bg-[#F2F7FA]">
                {data.status_id === 1 ? (
                  <>
                    <Button
                      variant="secondary"
                      className="bg-blue-200 hover:bg-blue-400"
                      onClick={(e) => {
                        e.stopPropagation();
                        setOpenCommentModal(true);
                      }}
                    >
                      Beri Tanggapan
                    </Button>

                    <Button
                      className=" w-[180]"
                      variant="destructive"
                      // onClick={(e) => {
                      //   e.stopPropagation();
                      //   handleReject();
                      // }}
                    >
                      Reject
                    </Button>

                    {userLevelId === "1" && (
                      <Button
                        // variant="ghost"
                        size="sm"
                        className="bg-green-600 hover:bg-green-700 text-white w-[180]"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleApproveGalery(data.id);
                        }}
                      >
                        <CheckCheck className="w-4 h-4 mr-1" />
                        Approve
                      </Button>
                    )}
                  </>
                ) : (
                  <Button
                    variant="secondary"
                    className="mx-auto"
                    onClick={(e) => {
                      e.stopPropagation();
                      setOpenViewDialog(false);
                    }}
                  >
                    Tutup
                  </Button>
                )}
              </div>
            )}
          </div>

          {/* <DialogFooter className="px-6 pb-6">
            <button
              onClick={onClose}
              className="bg-gray-300 text-gray-700 px-6 py-2 rounded-lg"
            >
              Tutup
            </button>
          </DialogFooter> */}
        </DialogContent>
      </Dialog>
      {openApproverHistory && (
        <div
          className="fixed inset-0 z-[60] flex items-center justify-center bg-black/50 p-4"
          onClick={() => setOpenApproverHistory(false)}
        >
          <div
            className="bg-white rounded-2xl shadow-2xl max-w-3xl w-full overflow-hidden"
            onClick={(e) => e.stopPropagation()}
          >
            {/* HEADER */}
            <div className="bg-gradient-to-br from-[#1F6779] to-[#0F6C75] text-white px-6 py-5 relative">
              <button
                onClick={() => setOpenApproverHistory(false)}
                className="absolute top-4 right-4 text-white/80 hover:text-white text-xl"
              >
                ✕
              </button>

              <h2 className="text-lg font-semibold">Approver History</h2>

              <div className="flex items-center gap-2 mt-3">
                <span className="bg-yellow-100 text-yellow-800 text-xs font-medium px-3 py-1 rounded-full">
                  Menunggu
                </span>
                <span className="bg-white text-[#0F6C75] text-xs font-medium px-3 py-1 rounded-full">
                  Banner
                </span>
                <span className="bg-white/20 text-white text-xs px-2 py-[2px] rounded-full">
                  1
                </span>
              </div>
            </div>

            {/* BODY */}
            <div className="p-6 grid grid-cols-[1fr_auto_1fr] gap-6 items-start">
              {/* LEFT TIMELINE */}
              <div className="relative space-y-6">
                {/* Upload */}
                <div className="flex flex-col items-center">
                  <span className="bg-[#C7DDE4] text-[#0F6C75] text-xs px-4 py-1 rounded-full">
                    Upload
                  </span>
                  <div className="w-px h-6 bg-gray-300" />
                </div>

                {/* Diterima */}
                <div className="relative bg-[#1F6779] text-white rounded-xl p-4">
                  <h4 className="font-semibold text-sm mb-2">Diterima</h4>
                  <span className="inline-block bg-[#E3EFF4] text-[#0F6C75] text-xs px-3 py-1 rounded-full">
                    Direview oleh: approver-jaecoo1
                  </span>
                </div>

                <div className="w-px h-6 bg-gray-300 mx-auto" />

                {/* Pending */}
                <div className="relative bg-[#B36A00] text-white rounded-xl p-4">
                  <h4 className="font-semibold text-sm mb-2">Pending</h4>
                  <span className="inline-block bg-[#FFF6CC] text-[#7A4A00] text-xs px-3 py-1 rounded-full">
                    Direview oleh: approver-jaecoo1
                  </span>
                </div>
              </div>

              {/* ARROW */}
              <div className="flex flex-col gap-20 text-gray-500 font-bold">
                <span>&gt;</span>
                <span>&gt;</span>
              </div>

              {/* RIGHT NOTES */}
              <div className="space-y-14">
                <div>
                  <div className="bg-[#C7DDE4] text-sm px-4 py-2 rounded-lg">
                    Catatan:
                  </div>
                </div>

                <div>
                  <div className="bg-[#FFF9C4] text-sm px-4 py-2 rounded-lg">
                    Catatan:
                  </div>
                </div>
              </div>
            </div>

            {/* FOOTER */}
            <div className="border-t bg-[#F2F7FA] text-center py-3">
              <button
                onClick={() => setOpenApproverHistory(false)}
                className="text-[#0F6C75] font-medium hover:underline"
              >
                Tutup
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
