import React, { useState, useEffect, useMemo } from "react";
import { UmkRequest } from "../../types/umk";
import { 
  generateUmkQrDataUrl, 
  generateUmkQrPayload, 
  generateUmkSecurityHash, 
  parseScannedUmkQr, 
  UmkQrValidationPayload 
} from "../../utils/umkQrGenerator";
import { 
  QrCode, 
  Camera, 
  CheckCircle2, 
  AlertCircle, 
  ShieldCheck, 
  Clock, 
  FileText, 
  Printer, 
  Receipt, 
  ArrowDownLeft, 
  ArrowRight, 
  RefreshCw, 
  X, 
  Check, 
  Copy, 
  Download, 
  Building2, 
  ExternalLink, 
  Layers, 
  UserCheck, 
  Search, 
  Sparkles,
  Zap
} from "lucide-react";

interface UmkQrValidationModalProps {
  isOpen: boolean;
  onClose: () => void;
  umkList: UmkRequest[];
  selectedUmkForScan?: UmkRequest | null;
  onApproveSettlement?: (umk: UmkRequest) => void;
  onOpenPrint?: (umk: UmkRequest, docType: any) => void;
}

export const UmkQrValidationModal: React.FC<UmkQrValidationModalProps> = ({
  isOpen,
  onClose,
  umkList,
  selectedUmkForScan,
  onApproveSettlement,
  onOpenPrint
}) => {
  if (!isOpen) return null;

  // Active target UMK being inspected
  const [activeUmkId, setActiveUmkId] = useState<string>(
    selectedUmkForScan ? selectedUmkForScan.id : umkList[0]?.id || ""
  );

  const [activeDocType, setActiveDocType] = useState<"LPJ_RECONCILIATION" | "VOUCHER_2_REALIZATION" | "VOUCHER_1_RETURN" | "VOUCHER_OUT_INITIAL">(
    "VOUCHER_2_REALIZATION"
  );

  // Scanner Simulator States
  const [isScanning, setIsScanning] = useState(false);
  const [scanSuccessMessage, setScanSuccessMessage] = useState<string | null>(null);
  const [manualInput, setManualInput] = useState("");
  const [activeQrDataUrl, setActiveQrDataUrl] = useState<string>("");
  const [isCopied, setIsCopied] = useState(false);

  // Selected UMK Object
  const currentUmk = useMemo(() => {
    return umkList.find((u) => u.id === activeUmkId) || umkList[0] || null;
  }, [umkList, activeUmkId]);

  // Generate QR image on UMK or docType change
  useEffect(() => {
    if (currentUmk) {
      generateUmkQrDataUrl(currentUmk, activeDocType)
        .then((url) => setActiveQrDataUrl(url))
        .catch((err) => console.error("Error generating QR:", err));
    }
  }, [currentUmk, activeDocType]);

  const formatRupiah = (val: number) => {
    return new Intl.NumberFormat("id-ID", {
      style: "currency",
      currency: "IDR",
      maximumFractionDigits: 0
    }).format(val);
  };

  const formatDateIndo = (dateStr: string) => {
    if (!dateStr || dateStr === "-") return "-";
    try {
      const d = new Date(dateStr);
      return d.toLocaleDateString("id-ID", {
        day: "numeric",
        month: "short",
        year: "numeric"
      });
    } catch {
      return dateStr;
    }
  };

  // Simulate Camera Scan Trigger
  const handleSimulateScan = (targetUmkId: string, docType: any = "VOUCHER_2_REALIZATION") => {
    setIsScanning(true);
    setScanSuccessMessage(null);

    setTimeout(() => {
      setActiveUmkId(targetUmkId);
      setActiveDocType(docType);
      setIsScanning(false);
      setScanSuccessMessage("Pindaian Dokumen Berhasil Terbaca!");
      setTimeout(() => setScanSuccessMessage(null), 3000);
    }, 900);
  };

  // Handle Manual Payload Validation
  const handleValidateManualInput = () => {
    if (!manualInput.trim()) return;
    setIsScanning(true);

    setTimeout(() => {
      const parsed = parseScannedUmkQr(manualInput.trim());
      if (parsed?.umkNumber) {
        const found = umkList.find(
          (u) => 
            u.umkNumber.toLowerCase() === parsed.umkNumber?.toLowerCase() ||
            u.realizationVoucher.voucherNumber.toLowerCase() === parsed.umkNumber?.toLowerCase() ||
            manualInput.toLowerCase().includes(u.umkNumber.toLowerCase())
        );

        if (found) {
          setActiveUmkId(found.id);
          if (parsed.docType) {
            setActiveDocType(parsed.docType as any);
          }
          setScanSuccessMessage(`Dokumen ${found.umkNumber} Valid & Ditemukan!`);
        } else {
          setScanSuccessMessage(`Data QR terbaca (${parsed.umkNumber}), menampilkan berkas aktif.`);
        }
      } else {
        // Fallback search by string in UMK list
        const match = umkList.find(
          (u) => 
            u.umkNumber.toLowerCase().includes(manualInput.toLowerCase()) ||
            u.realizationVoucher.voucherNumber.toLowerCase().includes(manualInput.toLowerCase())
        );
        if (match) {
          setActiveUmkId(match.id);
          setScanSuccessMessage(`Dokumen ${match.umkNumber} Berhasil Divalidasi!`);
        } else {
          alert("Kode QR / Nomor dokumen tidak ditemukan dalam database UMK!");
        }
      }
      setIsScanning(false);
      setTimeout(() => setScanSuccessMessage(null), 3000);
    }, 600);
  };

  // Copy QR Payload to Clipboard
  const handleCopyPayload = () => {
    if (!currentUmk) return;
    const payload = generateUmkQrPayload(currentUmk, activeDocType);
    navigator.clipboard.writeText(JSON.stringify(payload, null, 2));
    setIsCopied(true);
    setTimeout(() => setIsCopied(false), 2000);
  };

  // Download QR Code PNG
  const handleDownloadQr = () => {
    if (!activeQrDataUrl || !currentUmk) return;
    const link = document.createElement("a");
    link.href = activeQrDataUrl;
    link.download = `QR_VERIFIKASI_${currentUmk.umkNumber.replace(/[\/\\]/g, "_")}_${activeDocType}.png`;
    link.click();
  };

  // Finance Approval Quick Action
  const handleFinanceQuickApprove = () => {
    if (!currentUmk || !onApproveSettlement) return;
    const updated: UmkRequest = {
      ...currentUmk,
      status: "Selesai (Reconciled)",
      isReconciled: true,
      realizationVoucher: {
        ...currentUmk.realizationVoucher,
        status: "Disahkan Keuangan",
        verifiedByFinanceName: "Hendra Wijaya, S.E., Ak., M.M. (CFO / Direktur Keuangan)",
        verifiedByFinanceNip: "197019950002",
        verifiedAt: `${new Date().toISOString().split("T")[0]} 11:30 WIB`
      },
      approvedByFinanceName: "Hendra Wijaya, S.E., Ak., M.M.",
      approvedByFinanceNip: "197019950002",
      approvedByFinanceAt: `${new Date().toISOString().split("T")[0]} 11:30 WIB`,
      updatedAt: new Date().toISOString()
    };
    onApproveSettlement(updated);
    setScanSuccessMessage("Dokumen Realisasi Berhasil Disahkan & Direkonsiliasi 100% Lunas!");
  };

  const securityHash = currentUmk ? generateUmkSecurityHash(currentUmk, activeDocType) : "";
  const payload = currentUmk ? generateUmkQrPayload(currentUmk, activeDocType) : null;

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto bg-slate-950/85 backdrop-blur-md flex justify-center items-start p-3 sm:p-6">
      <div className="bg-slate-900 border border-slate-700 rounded-3xl w-full max-w-6xl shadow-2xl overflow-hidden my-4 text-slate-100 flex flex-col">
        
        {/* Modal Top Header */}
        <div className="bg-gradient-to-r from-slate-950 via-slate-900 to-emerald-950/60 p-5 sm:p-6 border-b border-slate-800 flex flex-wrap items-center justify-between gap-4">
          <div className="flex items-center gap-3.5">
            <div className="p-3 bg-gradient-to-br from-emerald-500 to-teal-600 rounded-2xl text-slate-950 shadow-lg shadow-emerald-500/20 shrink-0">
              <QrCode className="w-6 h-6 font-black" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <span className="text-[10px] font-black uppercase tracking-wider bg-emerald-400 text-slate-950 px-2.5 py-0.5 rounded font-mono">
                  SISTEM PEMINDAI QR DOKUMEN REALISASI UMK
                </span>
                <span className="text-[10px] text-sky-400 font-mono font-bold bg-sky-500/10 border border-sky-500/30 px-2 py-0.5 rounded">
                  Verifikasi Tim Keuangan & Auditor
                </span>
              </div>
              <h2 className="text-lg sm:text-xl font-black text-white mt-1">
                Validasi Keaslian Dokumen & Status Workflow Persetujuan
              </h2>
              <p className="text-xs text-slate-300">
                Pindai QR code fisik pada dokumen Voucher 2 Realisasi UMK atau Lembar LPJ untuk memeriksa keabsahan bukti kuitansi dan tahapan otorisasi keuangan secara instan.
              </p>
            </div>
          </div>

          <button
            onClick={onClose}
            className="p-2 text-slate-400 hover:text-white hover:bg-slate-800 rounded-xl transition-colors cursor-pointer"
          >
            <X className="w-6 h-6" />
          </button>
        </div>

        {/* Modal Body: 2 Columns */}
        <div className="p-5 sm:p-6 grid grid-cols-1 lg:grid-cols-12 gap-6">
          
          {/* ========================================================================= */}
          {/* LEFT COLUMN: SCANNER / DOCUMENT SELECTOR & LIVE QR CODE (5 COLS) */}
          {/* ========================================================================= */}
          <div className="lg:col-span-5 space-y-5">
            
            {/* Camera / Scan Viewport Box */}
            <div className="bg-slate-950 border-2 border-emerald-500/40 rounded-2xl p-5 space-y-4 shadow-inner relative overflow-hidden">
              
              {/* Scan Laser Animation when scanning */}
              {isScanning && (
                <div className="absolute inset-0 bg-emerald-500/10 z-10 flex flex-col items-center justify-center pointer-events-none">
                  <div className="w-full h-1 bg-gradient-to-r from-transparent via-emerald-400 to-transparent animate-pulse absolute top-1/2 -translate-y-1/2" />
                  <div className="p-3 bg-slate-900/90 rounded-xl border border-emerald-500 text-emerald-400 font-mono text-xs font-bold shadow-xl animate-bounce">
                    ⚡ Memindai QR Code Dokumen Fisik...
                  </div>
                </div>
              )}

              <div className="flex items-center justify-between border-b border-slate-800 pb-3">
                <span className="text-xs font-black uppercase tracking-wider text-emerald-400 flex items-center gap-1.5 font-mono">
                  <Camera className="w-4 h-4" />
                  <span>QR Code Real-Time Dokumen</span>
                </span>
                <span className="text-[10px] font-mono bg-slate-800 text-slate-300 px-2 py-0.5 rounded">
                  Format: ISO/IEC 18004
                </span>
              </div>

              {/* QR Code Canvas Display */}
              <div className="flex flex-col items-center justify-center p-4 bg-white rounded-2xl shadow-lg relative group">
                {activeQrDataUrl ? (
                  <img
                    src={activeQrDataUrl}
                    alt="QR Code Verifikasi Dokumen Realisasi UMK"
                    className="w-48 h-48 sm:w-56 sm:h-56 object-contain rounded-lg"
                  />
                ) : (
                  <div className="w-48 h-48 flex items-center justify-center text-slate-600 font-mono text-xs">
                    Membuat QR Code...
                  </div>
                )}

                {/* Digital Stamp Seal Badge */}
                <div className="mt-3 w-full bg-slate-950 text-white p-2 rounded-xl border border-slate-800 text-center space-y-0.5">
                  <div className="text-[10px] font-mono font-bold text-emerald-400 flex items-center justify-center gap-1">
                    <ShieldCheck className="w-3.5 h-3.5 text-emerald-400" />
                    <span>PT MEDIAN CLOUD • DIGITAL VERIFIED SEAL</span>
                  </div>
                  <div className="text-[9px] font-mono text-slate-400 truncate">
                    Hash: {securityHash}
                  </div>
                </div>
              </div>

              {/* Document Type Selector Switcher */}
              <div className="space-y-1.5">
                <label className="text-[11px] font-bold text-slate-300 block">
                  Tipe Dokumen Fisik Yang Diverifikasi:
                </label>
                <div className="grid grid-cols-2 gap-2 text-[11px] font-bold">
                  <button
                    onClick={() => setActiveDocType("VOUCHER_2_REALIZATION")}
                    className={`p-2 rounded-xl border transition-all text-left ${
                      activeDocType === "VOUCHER_2_REALIZATION"
                        ? "bg-sky-500/20 border-sky-500 text-sky-300 shadow"
                        : "bg-slate-900 border-slate-800 text-slate-400 hover:text-white"
                    }`}
                  >
                    <div className="font-mono text-[10px] text-sky-400">VOUCHER 2</div>
                    <div className="truncate">Realisasi Belanja</div>
                  </button>

                  <button
                    onClick={() => setActiveDocType("LPJ_RECONCILIATION")}
                    className={`p-2 rounded-xl border transition-all text-left ${
                      activeDocType === "LPJ_RECONCILIATION"
                        ? "bg-emerald-500/20 border-emerald-500 text-emerald-300 shadow"
                        : "bg-slate-900 border-slate-800 text-slate-400 hover:text-white"
                    }`}
                  >
                    <div className="font-mono text-[10px] text-emerald-400">REKONSILIASI</div>
                    <div className="truncate">Lembar LPJ Lengkap</div>
                  </button>

                  <button
                    onClick={() => setActiveDocType("VOUCHER_1_RETURN")}
                    className={`p-2 rounded-xl border transition-all text-left ${
                      activeDocType === "VOUCHER_1_RETURN"
                        ? "bg-amber-500/20 border-amber-500 text-amber-300 shadow"
                        : "bg-slate-900 border-slate-800 text-slate-400 hover:text-white"
                    }`}
                  >
                    <div className="font-mono text-[10px] text-amber-400">VOUCHER 1</div>
                    <div className="truncate">Setor Sisa Kas</div>
                  </button>

                  <button
                    onClick={() => setActiveDocType("VOUCHER_OUT_INITIAL")}
                    className={`p-2 rounded-xl border transition-all text-left ${
                      activeDocType === "VOUCHER_OUT_INITIAL"
                        ? "bg-purple-500/20 border-purple-500 text-purple-300 shadow"
                        : "bg-slate-900 border-slate-800 text-slate-400 hover:text-white"
                    }`}
                  >
                    <div className="font-mono text-[10px] text-purple-400">VOUCHER AWAL</div>
                    <div className="truncate">Pencairan Dana UMK</div>
                  </button>
                </div>
              </div>

              {/* Action Buttons for QR */}
              <div className="flex items-center gap-2 pt-1">
                <button
                  onClick={handleCopyPayload}
                  className="flex-1 py-2 bg-slate-900 hover:bg-slate-800 text-slate-200 font-bold text-xs rounded-xl border border-slate-700 flex items-center justify-center gap-1.5 transition-all cursor-pointer"
                >
                  <Copy className="w-3.5 h-3.5 text-sky-400" />
                  <span>{isCopied ? "Payload Disalin!" : "Salin Data QR"}</span>
                </button>

                <button
                  onClick={handleDownloadQr}
                  className="flex-1 py-2 bg-slate-900 hover:bg-slate-800 text-slate-200 font-bold text-xs rounded-xl border border-slate-700 flex items-center justify-center gap-1.5 transition-all cursor-pointer"
                >
                  <Download className="w-3.5 h-3.5 text-emerald-400" />
                  <span>Unduh Gambar QR</span>
                </button>
              </div>

            </div>

            {/* Quick Test / Switch Document from Database */}
            <div className="bg-slate-950/70 border border-slate-800 rounded-2xl p-4 space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-xs font-bold text-slate-300 uppercase tracking-wide flex items-center gap-1.5">
                  <Zap className="w-3.5 h-3.5 text-amber-400" />
                  <span>Pilih Cepat Dokumen Fisik UMK (Simulasi Scan)</span>
                </span>
                <span className="text-[10px] font-mono text-slate-400">{umkList.length} Berkas</span>
              </div>

              <div className="space-y-2 max-h-48 overflow-y-auto pr-1">
                {umkList.map((item) => (
                  <button
                    key={item.id}
                    onClick={() => handleSimulateScan(item.id, "VOUCHER_2_REALIZATION")}
                    className={`w-full p-2.5 rounded-xl border text-left flex items-center justify-between gap-2 transition-all ${
                      item.id === activeUmkId 
                        ? "bg-emerald-500/20 border-emerald-500 text-white shadow" 
                        : "bg-slate-900/80 border-slate-800 text-slate-400 hover:bg-slate-800 hover:text-white"
                    }`}
                  >
                    <div className="space-y-0.5 truncate">
                      <div className="font-mono text-xs font-bold text-white flex items-center gap-1.5">
                        <span>{item.umkNumber}</span>
                        <span className={`text-[9px] px-1.5 py-0.2 rounded font-sans font-bold ${
                          item.status === "Selesai (Reconciled)" || item.status === "LPJ Diverifikasi Keuangan"
                            ? "bg-emerald-500/30 text-emerald-300"
                            : "bg-amber-500/30 text-amber-300"
                        }`}>
                          {item.status}
                        </span>
                      </div>
                      <div className="text-[10px] text-slate-400 truncate">
                        {item.periodName} • PIC: {item.requesterName}
                      </div>
                    </div>
                    <div className="font-mono text-xs font-bold text-sky-400 shrink-0">
                      {formatRupiah(item.realizationVoucher.totalRealizedAmount)}
                    </div>
                  </button>
                ))}
              </div>

              {/* Manual Input Search/Paste Bar */}
              <div className="pt-2 border-t border-slate-800 flex gap-2">
                <input
                  type="text"
                  value={manualInput}
                  onChange={(e) => setManualInput(e.target.value)}
                  placeholder="Tempel teks QR / nomor UMK..."
                  className="flex-1 px-3 py-1.5 bg-slate-900 border border-slate-800 rounded-lg text-xs text-white placeholder-slate-500 focus:outline-none focus:border-emerald-500"
                  onKeyDown={(e) => {
                    if (e.key === "Enter") handleValidateManualInput();
                  }}
                />
                <button
                  onClick={handleValidateManualInput}
                  className="px-3 py-1.5 bg-emerald-500 hover:bg-emerald-400 text-slate-950 font-bold text-xs rounded-lg transition-all cursor-pointer"
                >
                  Validasi
                </button>
              </div>

            </div>

          </div>

          {/* ========================================================================= */}
          {/* RIGHT COLUMN: WORKFLOW STATUS & VALIDATION REPORT (7 COLS) */}
          {/* ========================================================================= */}
          <div className="lg:col-span-7 space-y-5">
            
            {/* Scan Success Banner */}
            {scanSuccessMessage && (
              <div className="p-3 bg-emerald-500/20 border border-emerald-500 rounded-2xl flex items-center gap-2 text-emerald-300 text-xs font-bold animate-fadeIn">
                <CheckCircle2 className="w-4 h-4 text-emerald-400 shrink-0" />
                <span>{scanSuccessMessage}</span>
              </div>
            )}

            {currentUmk ? (
              <div className="space-y-5">
                
                {/* 1. Authentic Document Verification Badge */}
                <div className="bg-slate-950 border-2 border-emerald-500/40 rounded-2xl p-4 sm:p-5 space-y-3 shadow-md">
                  <div className="flex flex-wrap items-center justify-between gap-2 border-b border-slate-800 pb-3">
                    <div className="flex items-center gap-2">
                      <div className="p-2 bg-emerald-500/20 text-emerald-400 rounded-xl">
                        <ShieldCheck className="w-5 h-5" />
                      </div>
                      <div>
                        <div className="text-[10px] font-bold uppercase tracking-wider text-emerald-400 font-mono">
                          STATUS VALIDASI OTENTIKASI SISTEM
                        </div>
                        <h3 className="text-sm sm:text-base font-black text-white">
                          DOKUMEN ASLI TERDAFTAR & TERVERIFIKASI
                        </h3>
                      </div>
                    </div>

                    <div className="text-right">
                      <span className="text-xs font-mono font-bold text-emerald-300 bg-emerald-500/20 border border-emerald-500/40 px-2.5 py-1 rounded-lg">
                        ● VERIFIED AUTHENTIC
                      </span>
                    </div>
                  </div>

                  {/* Metadata Grid */}
                  <div className="grid grid-cols-2 sm:grid-cols-3 gap-3 text-xs">
                    <div className="bg-slate-900/80 p-2.5 rounded-xl border border-slate-800">
                      <div className="text-[10px] text-slate-400 font-semibold">Nomor Induk UMK:</div>
                      <div className="font-mono font-bold text-white mt-0.5">{currentUmk.umkNumber}</div>
                    </div>

                    <div className="bg-slate-900/80 p-2.5 rounded-xl border border-slate-800">
                      <div className="text-[10px] text-slate-400 font-semibold">Nomor Voucher Fisik:</div>
                      <div className="font-mono font-bold text-sky-400 mt-0.5">
                        {activeDocType === "VOUCHER_2_REALIZATION"
                          ? currentUmk.realizationVoucher.voucherNumber
                          : activeDocType === "VOUCHER_1_RETURN"
                          ? currentUmk.returnVoucher.voucherNumber
                          : activeDocType === "VOUCHER_OUT_INITIAL"
                          ? currentUmk.disbursementVoucher.voucherNumber
                          : `${currentUmk.realizationVoucher.voucherNumber} & ${currentUmk.returnVoucher.voucherNumber}`}
                      </div>
                    </div>

                    <div className="bg-slate-900/80 p-2.5 rounded-xl border border-slate-800">
                      <div className="text-[10px] text-slate-400 font-semibold">Akun Anggaran Induk:</div>
                      <div className="font-mono font-bold text-purple-300 mt-0.5">
                        {currentUmk.disbursementVoucher.budgetAccountCode}
                      </div>
                    </div>

                    <div className="bg-slate-900/80 p-2.5 rounded-xl border border-slate-800">
                      <div className="text-[10px] text-slate-400 font-semibold">Penanggung Jawab (PIC):</div>
                      <div className="font-bold text-slate-200 mt-0.5 truncate">
                        {currentUmk.requesterName}
                      </div>
                      <div className="text-[9px] font-mono text-slate-400">NIP: {currentUmk.requesterNip}</div>
                    </div>

                    <div className="bg-slate-900/80 p-2.5 rounded-xl border border-slate-800">
                      <div className="text-[10px] text-slate-400 font-semibold">Pemegang Kasir GA:</div>
                      <div className="font-bold text-slate-200 mt-0.5 truncate">
                        {currentUmk.custodianName}
                      </div>
                      <div className="text-[9px] font-mono text-slate-400">NIP: {currentUmk.custodianNip}</div>
                    </div>

                    <div className="bg-slate-900/80 p-2.5 rounded-xl border border-slate-800">
                      <div className="text-[10px] text-slate-400 font-semibold">Tenggat LPJ (14 Hari):</div>
                      <div className="font-mono font-bold text-amber-300 mt-0.5">
                        {formatDateIndo(currentUmk.dueDate)}
                      </div>
                    </div>
                  </div>
                </div>

                {/* 2. Visual Interactive Workflow Pipeline Stepper */}
                <div className="bg-slate-950 border border-slate-800 rounded-2xl p-5 space-y-4 shadow-md">
                  <div className="flex items-center justify-between border-b border-slate-800 pb-2.5">
                    <span className="text-xs font-bold text-white uppercase tracking-wider flex items-center gap-2">
                      <Clock className="w-4 h-4 text-sky-400" />
                      <span>Tahapan Workflow Persetujuan & Otorisasi Keuangan</span>
                    </span>
                    <span className="text-[10px] font-mono text-slate-400">
                      Tahap Aktif: <strong className="text-emerald-400">{currentUmk.status}</strong>
                    </span>
                  </div>

                  {/* Stepper Steps */}
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 text-xs">
                    
                    {/* Step 1 */}
                    <div className="p-3 bg-slate-900 rounded-xl border border-emerald-500/40 space-y-1 relative">
                      <div className="flex items-center justify-between">
                        <span className="text-[10px] font-mono font-bold text-emerald-400">TAHAP 1</span>
                        <CheckCircle2 className="w-4 h-4 text-emerald-400" />
                      </div>
                      <div className="font-bold text-white text-[11px]">1. Pengajuan UMK GA</div>
                      <div className="text-[10px] text-slate-400">
                        Oleh: {currentUmk.requesterName} ({formatDateIndo(currentUmk.requestDate)})
                      </div>
                    </div>

                    {/* Step 2 */}
                    <div className={`p-3 bg-slate-900 rounded-xl border space-y-1 relative ${
                      currentUmk.status !== "Draft" && currentUmk.status !== "Menunggu Approval Keuangan"
                        ? "border-emerald-500/40 text-emerald-300"
                        : "border-amber-500/40 text-amber-300"
                    }`}>
                      <div className="flex items-center justify-between">
                        <span className="text-[10px] font-mono font-bold">TAHAP 2</span>
                        {currentUmk.status !== "Draft" && currentUmk.status !== "Menunggu Approval Keuangan" ? (
                          <CheckCircle2 className="w-4 h-4 text-emerald-400" />
                        ) : (
                          <Clock className="w-4 h-4 text-amber-400 animate-spin" />
                        )}
                      </div>
                      <div className="font-bold text-white text-[11px]">2. Pencairan Kas Keluar</div>
                      <div className="text-[10px] text-slate-400">
                        {formatRupiah(currentUmk.disbursementVoucher.amount)} ({formatDateIndo(currentUmk.disbursementDate)})
                      </div>
                    </div>

                    {/* Step 3 */}
                    <div className={`p-3 bg-slate-900 rounded-xl border space-y-1 relative ${
                      currentUmk.isReconciled || currentUmk.status === "Selesai (Reconciled)" || currentUmk.status === "LPJ Diverifikasi Keuangan"
                        ? "border-emerald-500/40 text-emerald-300"
                        : "border-sky-500/40 text-sky-300"
                    }`}>
                      <div className="flex items-center justify-between">
                        <span className="text-[10px] font-mono font-bold">TAHAP 3</span>
                        {currentUmk.isReconciled || currentUmk.status === "Selesai (Reconciled)" || currentUmk.status === "LPJ Diverifikasi Keuangan" ? (
                          <CheckCircle2 className="w-4 h-4 text-emerald-400" />
                        ) : (
                          <Clock className="w-4 h-4 text-sky-400" />
                        )}
                      </div>
                      <div className="font-bold text-white text-[11px]">3. LPJ & Rekonsiliasi 2 Voucher</div>
                      <div className="text-[10px] text-slate-400">
                        {currentUmk.isReconciled ? "✓ 100% Klir & Disahkan" : "Menunggu Pengesahan"}
                      </div>
                    </div>

                  </div>
                </div>

                {/* 3. Financial Breakdown & Attached Receipts */}
                <div className="bg-slate-950 border border-slate-800 rounded-2xl p-5 space-y-3 shadow-md">
                  <div className="flex items-center justify-between border-b border-slate-800 pb-2.5">
                    <span className="text-xs font-bold text-white uppercase tracking-wider flex items-center gap-2">
                      <Receipt className="w-4 h-4 text-emerald-400" />
                      <span>Rincian Realisasi Belanja ({currentUmk.realizationVoucher.expenseItems.length} Kuitansi Sah)</span>
                    </span>
                    <div className="font-mono text-xs font-bold text-emerald-400">
                      Total: {formatRupiah(currentUmk.realizationVoucher.totalRealizedAmount)}
                    </div>
                  </div>

                  {/* Item List */}
                  <div className="space-y-2 max-h-44 overflow-y-auto pr-1">
                    {currentUmk.realizationVoucher.expenseItems.map((item, idx) => (
                      <div
                        key={item.id}
                        className="p-2.5 bg-slate-900 rounded-xl border border-slate-800 flex items-center justify-between gap-3 text-xs"
                      >
                        <div className="space-y-0.5 truncate">
                          <div className="font-bold text-white flex items-center gap-2">
                            <span className="font-mono text-[10px] text-purple-400 bg-purple-500/20 px-1.5 rounded">
                              {item.budgetCode}
                            </span>
                            <span className="truncate">{item.itemDescription}</span>
                          </div>
                          <div className="text-[10px] text-slate-400 font-mono">
                            No. Kuitansi: <strong className="text-slate-200">{item.receiptNumber}</strong> • {item.vendorName}
                          </div>
                        </div>

                        <div className="text-right shrink-0">
                          <div className="font-mono font-bold text-sky-400">
                            {formatRupiah(item.amount)}
                          </div>
                          <div className={`text-[9px] font-bold ${
                            item.isExpendables ? "text-emerald-400" : "text-slate-400"
                          }`}>
                            {item.isExpendables ? "Expendables" : "Operasional"}
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>

                  {/* Balance Summary Box */}
                  <div className="p-3 bg-slate-900/90 rounded-xl border border-slate-800 flex flex-wrap items-center justify-between gap-2 text-xs font-mono">
                    <div>
                      <span className="text-slate-400">Dana Awal: </span>
                      <strong className="text-white">{formatRupiah(currentUmk.disbursementVoucher.amount)}</strong>
                    </div>
                    <div>
                      <span className="text-slate-400">Realisasi (V2): </span>
                      <strong className="text-sky-400">{formatRupiah(currentUmk.realizationVoucher.totalRealizedAmount)}</strong>
                    </div>
                    <div>
                      <span className="text-slate-400">Setor Sisa (V1): </span>
                      <strong className="text-amber-400">{formatRupiah(currentUmk.returnVoucher.returnAmount)}</strong>
                    </div>
                    <div>
                      <span className="text-slate-400">Status Saldo: </span>
                      <span className="text-emerald-400 font-bold">
                        {currentUmk.balanceAmount === 0 ? "✓ NIHIL (0)" : formatRupiah(currentUmk.balanceAmount)}
                      </span>
                    </div>
                  </div>
                </div>

                {/* 4. Action Buttons for Finance Team */}
                <div className="flex flex-wrap items-center justify-end gap-3 pt-2">
                  
                  {/* Action 1: Instant Approval / Reconciliation */}
                  {(!currentUmk.isReconciled || currentUmk.status !== "Selesai (Reconciled)") && (
                    <button
                      onClick={handleFinanceQuickApprove}
                      className="px-5 py-2.5 bg-gradient-to-r from-emerald-500 to-teal-600 hover:from-emerald-400 hover:to-teal-500 text-slate-950 font-black text-xs uppercase tracking-wider rounded-xl shadow-lg shadow-emerald-500/25 flex items-center gap-2 transition-all cursor-pointer"
                    >
                      <Check className="w-4 h-4 font-black" />
                      <span>Sahkan & Rekonsiliasi Dokumen LPJ (Tim Keuangan)</span>
                    </button>
                  )}

                  {/* Action 2: Open Print Modal */}
                  {onOpenPrint && (
                    <button
                      onClick={() => {
                        onClose();
                        onOpenPrint(currentUmk, activeDocType);
                      }}
                      className="px-4 py-2.5 bg-slate-800 hover:bg-slate-700 text-slate-200 font-bold text-xs rounded-xl border border-slate-700 flex items-center gap-2 transition-all cursor-pointer"
                    >
                      <Printer className="w-4 h-4 text-emerald-400" />
                      <span>Cetak Dokumen Lengkap Ber-QR</span>
                    </button>
                  )}

                  <button
                    onClick={onClose}
                    className="px-4 py-2.5 bg-slate-900 hover:bg-slate-800 text-slate-400 hover:text-white font-bold text-xs rounded-xl border border-slate-800 transition-all cursor-pointer"
                  >
                    Tutup
                  </button>
                </div>

              </div>
            ) : (
              <div className="bg-slate-950 p-12 text-center rounded-2xl border border-slate-800 space-y-3">
                <AlertCircle className="w-10 h-10 text-slate-600 mx-auto" />
                <div className="text-sm font-bold text-slate-300">Pilih dokumen fisik di sisi kiri untuk memvalidasi</div>
              </div>
            )}

          </div>

        </div>

      </div>
    </div>
  );
};

export default UmkQrValidationModal;
