import React, { useState } from "react";
import { 
  UmkRequest, 
  UmkExpenseItem, 
  UMK_BUDGET_ACCOUNTS, 
  ReceiptType, 
  calculateUmkDeadline 
} from "../../types/umk";
import { 
  X, 
  Plus, 
  Trash2, 
  Receipt, 
  DollarSign, 
  CheckCircle2, 
  AlertCircle, 
  Clock, 
  Printer, 
  FileText, 
  ArrowDownLeft, 
  ArrowUpRight,
  Calculator,
  Building2,
  Calendar
} from "lucide-react";

interface UmkSettlementModalProps {
  umk: UmkRequest;
  isOpen: boolean;
  onClose: () => void;
  onSave: (updatedUmk: UmkRequest) => void;
  onOpenPrint: (umk: UmkRequest, docType: any) => void;
}

export const UmkSettlementModal: React.FC<UmkSettlementModalProps> = ({
  umk,
  isOpen,
  onClose,
  onSave,
  onOpenPrint
}) => {
  const todayStr = new Date().toISOString().split("T")[0];

  // Voucher 2 Realization items
  const [expenseItems, setExpenseItems] = useState<UmkExpenseItem[]>(
    umk.realizationVoucher.expenseItems.length > 0 
      ? [...umk.realizationVoucher.expenseItems] 
      : [
          {
            id: `exp-${Date.now()}-1`,
            transactionDate: todayStr,
            budgetCode: "5102.01",
            budgetName: "5102.01 - Expendables: ATK & Perlengkapan Kantor",
            category: "EXPENDABLES",
            isExpendables: true,
            itemDescription: "",
            vendorName: "",
            receiptNumber: "",
            receiptType: "Struk Kasir Sah / Invoice",
            amount: 0,
            notes: ""
          }
        ]
  );

  const [realizationNotes, setRealizationNotes] = useState(umk.realizationVoucher.notes || "");
  const [submissionDate, setSubmissionDate] = useState(
    umk.realizationVoucher.submissionDate !== "-" ? umk.realizationVoucher.submissionDate : todayStr
  );

  // Voucher 1 Return items
  const [returnAmount, setReturnAmount] = useState<number>(umk.returnVoucher.returnAmount || 0);
  const [returnDate, setReturnDate] = useState(
    umk.returnVoucher.returnDate !== "-" ? umk.returnVoucher.returnDate : todayStr
  );
  const [returnMethod, setReturnMethod] = useState<"Setor Tunai Kasir Keuangan" | "Transfer Kas Perusahaan">(
    umk.returnVoucher.returnMethod || "Setor Tunai Kasir Keuangan"
  );
  const [receiptNumber, setReceiptNumber] = useState(
    umk.returnVoucher.receiptNumber !== "-" ? umk.returnVoucher.receiptNumber : `STS-KEU/2026/08/${Math.floor(100 + Math.random() * 900)}`
  );
  const [depositAccount, setDepositAccount] = useState(
    umk.returnVoucher.depositAccount || "Kasir Perbendaharaan Keuangan Pusat"
  );
  const [receivedByName, setReceivedByName] = useState(
    umk.returnVoucher.receivedByName !== "-" ? umk.returnVoucher.receivedByName : "Dewi Lestari, S.E. (Kasir Pusat Keuangan)"
  );
  const [receivedByNip, setReceivedByNip] = useState(
    umk.returnVoucher.receivedByNip !== "-" ? umk.returnVoucher.receivedByNip : "199120150028"
  );
  const [returnNotes, setReturnNotes] = useState(umk.returnVoucher.notes || "");

  // Calculations
  const initialAmount = umk.disbursementVoucher.amount;
  const totalRealized = expenseItems.reduce((acc, item) => acc + (Number(item.amount) || 0), 0);
  const totalExpendables = expenseItems
    .filter((item) => item.isExpendables)
    .reduce((acc, item) => acc + (Number(item.amount) || 0), 0);
  const totalNonExpendables = totalRealized - totalExpendables;

  const calculatedBalanceRemaining = initialAmount - totalRealized;
  const totalAccounted = totalRealized + returnAmount;
  const finalDiscrepancy = initialAmount - totalAccounted;

  const deadline = calculateUmkDeadline(umk.disbursementDate, umk.dueDate, umk.isReconciled);

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

  // Add new line item
  const handleAddItem = () => {
    const defaultAccount = UMK_BUDGET_ACCOUNTS[0];
    const newItem: UmkExpenseItem = {
      id: `exp-${Date.now()}-${Math.floor(Math.random() * 1000)}`,
      transactionDate: todayStr,
      budgetCode: defaultAccount.code,
      budgetName: defaultAccount.name,
      category: defaultAccount.category,
      isExpendables: defaultAccount.isExpendables,
      itemDescription: "",
      vendorName: "",
      receiptNumber: "",
      receiptType: "Struk Kasir Sah / Invoice",
      amount: 0,
      notes: ""
    };
    setExpenseItems([...expenseItems, newItem]);
  };

  // Remove item
  const handleRemoveItem = (id: string) => {
    if (expenseItems.length <= 1) {
      alert("Minimal harus ada satu (1) baris rincian belanja kas kecil.");
      return;
    }
    setExpenseItems(expenseItems.filter((i) => i.id !== id));
  };

  // Update item field
  const handleItemChange = (id: string, field: keyof UmkExpenseItem, value: any) => {
    setExpenseItems(
      expenseItems.map((item) => {
        if (item.id !== id) return item;

        if (field === "budgetCode") {
          const selectedAcct = UMK_BUDGET_ACCOUNTS.find((a) => a.code === value);
          if (selectedAcct) {
            return {
              ...item,
              budgetCode: selectedAcct.code,
              budgetName: selectedAcct.name,
              category: selectedAcct.category,
              isExpendables: selectedAcct.isExpendables
            };
          }
        }

        return {
          ...item,
          [field]: field === "amount" ? Number(value) || 0 : value
        };
      })
    );
  };

  // Auto fill return amount to balance remaining
  const handleAutoFillReturn = () => {
    if (calculatedBalanceRemaining > 0) {
      setReturnAmount(calculatedBalanceRemaining);
    } else {
      setReturnAmount(0);
    }
  };

  // Save changes
  const handleSave = (shouldSubmit: boolean) => {
    // Validate that there is at least one item with description and valid receipt
    const hasInvalidItem = expenseItems.some(
      (item) => !item.itemDescription.trim() || !item.receiptNumber.trim() || item.amount <= 0
    );

    if (shouldSubmit && hasInvalidItem) {
      alert("Mohon lengkapi seluruh rincian belanja: Deskripsi, Nomor Kuitansi Sah, dan Jumlah Nominal (> 0) pada setiap baris.");
      return;
    }

    const returnStatus = returnAmount > 0 ? "Disetor Penuh" : calculatedBalanceRemaining === 0 ? "Nihil (Habis Terpakai)" : "Belum Disetor";

    const updatedUmk: UmkRequest = {
      ...umk,
      status: shouldSubmit ? "LPJ Diverifikasi Keuangan" : "Menunggu LPJ Keuangan",
      
      // Update Voucher 1
      returnVoucher: {
        ...umk.returnVoucher,
        voucherNumber: umk.returnVoucher.voucherNumber || `V-RET-UMK/GA/2026/08/${Math.floor(100 + Math.random() * 900)}`,
        returnAmount,
        returnDate,
        returnMethod,
        depositAccount,
        receiptNumber,
        receivedByNip,
        receivedByName,
        status: returnStatus,
        notes: returnNotes
      },

      // Update Voucher 2
      realizationVoucher: {
        ...umk.realizationVoucher,
        voucherNumber: umk.realizationVoucher.voucherNumber || `V-REAL-UMK/GA/2026/08/${Math.floor(100 + Math.random() * 900)}`,
        totalRealizedAmount: totalRealized,
        totalExpendablesAmount: totalExpendables,
        totalNonExpendablesAmount: totalNonExpendables,
        submissionDate,
        status: shouldSubmit ? "Disahkan Keuangan" : "Diajukan ke Keuangan",
        notes: realizationNotes,
        expenseItems
      },

      balanceAmount: finalDiscrepancy,
      isReconciled: finalDiscrepancy === 0,
      updatedAt: new Date().toISOString()
    };

    onSave(updatedUmk);
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto bg-slate-950/85 backdrop-blur-sm flex justify-center items-start p-2 sm:p-5">
      <div className="bg-slate-900 border border-slate-700 rounded-2xl w-full max-w-6xl shadow-2xl overflow-hidden my-3 text-slate-100">
        
        {/* Header */}
        <div className="bg-gradient-to-r from-slate-900 via-sky-950/60 to-slate-900 px-6 py-4 border-b border-slate-700 flex flex-wrap items-center justify-between gap-3">
          <div className="flex items-center gap-3">
            <div className="p-2.5 bg-sky-500/20 border border-sky-500/40 text-sky-400 rounded-xl">
              <Receipt className="w-5 h-5" />
            </div>
            <div>
              <h2 className="text-base font-bold text-white flex items-center gap-2">
                Pertanggungjawaban (LPJ) & 2 Voucher Kas Kecil GA
                <span className="text-xs font-mono font-bold bg-sky-500/20 text-sky-300 border border-sky-500/30 px-2 py-0.5 rounded">
                  {umk.umkNumber}
                </span>
              </h2>
              <p className="text-xs text-slate-400">
                Pencatatan realisasi kuitansi sah (Voucher 2) dan pengembalian sisa kas (Voucher 1)
              </p>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <button
              onClick={() => onOpenPrint(umk, "LPJ_RECONCILIATION")}
              className="px-3.5 py-1.5 bg-slate-800 hover:bg-slate-700 border border-slate-600 text-slate-200 text-xs font-bold rounded-lg flex items-center gap-1.5 transition-all cursor-pointer"
            >
              <Printer className="w-3.5 h-3.5 text-emerald-400" />
              <span>Cetak LPJ</span>
            </button>
            <button
              onClick={onClose}
              className="p-1.5 text-slate-400 hover:text-white hover:bg-slate-800 rounded-lg transition-colors"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* Top Summary Banner */}
        <div className="bg-slate-950/70 p-4 border-b border-slate-800 grid grid-cols-2 lg:grid-cols-5 gap-3 text-xs">
          
          {/* Card 1: Dana Awal UMK */}
          <div className="bg-slate-900 border border-slate-700/80 p-3 rounded-xl space-y-1">
            <div className="text-[10px] text-slate-400 uppercase font-bold flex items-center justify-between">
              <span>Dana Awal UMK</span>
              <span className="text-purple-400 font-mono">1 AKUN</span>
            </div>
            <div className="text-sm sm:text-base font-black text-purple-300 font-mono">
              {formatRupiah(initialAmount)}
            </div>
            <div className="text-[10px] text-slate-400 truncate">
              {umk.disbursementVoucher.budgetAccountCode} - Kas Kecil GA
            </div>
          </div>

          {/* Card 2: Realisasi Belanja (Voucher 2) */}
          <div className="bg-slate-900 border border-sky-500/30 p-3 rounded-xl space-y-1">
            <div className="text-[10px] text-sky-400 uppercase font-bold flex items-center justify-between">
              <span>Voucher 2: Realisasi</span>
              <span className="text-[10px] bg-sky-500/20 text-sky-300 px-1 rounded font-mono">
                {expenseItems.length} Nota
              </span>
            </div>
            <div className="text-sm sm:text-base font-black text-sky-300 font-mono">
              {formatRupiah(totalRealized)}
            </div>
            <div className="text-[10px] text-emerald-400 font-mono">
              Expendables: {formatRupiah(totalExpendables)}
            </div>
          </div>

          {/* Card 3: Sisa Belanja Belum Disetor */}
          <div className="bg-slate-900 border border-slate-700/80 p-3 rounded-xl space-y-1">
            <div className="text-[10px] text-slate-400 uppercase font-bold">
              Sisa Saldo Kas Kecil
            </div>
            <div className={`text-sm sm:text-base font-black font-mono ${
              calculatedBalanceRemaining >= 0 ? "text-amber-300" : "text-rose-400"
            }`}>
              {formatRupiah(calculatedBalanceRemaining)}
            </div>
            <div className="text-[10px] text-slate-400">
              {calculatedBalanceRemaining > 0 ? "Wajib Disetor ke Kasir" : calculatedBalanceRemaining === 0 ? "Habis Terpakai" : "Kurang Bayar (Reimburse)"}
            </div>
          </div>

          {/* Card 4: Voucher 1 Pengembalian */}
          <div className="bg-slate-900 border border-amber-500/30 p-3 rounded-xl space-y-1">
            <div className="text-[10px] text-amber-400 uppercase font-bold flex items-center justify-between">
              <span>Voucher 1: Setor Sisa</span>
              <button
                type="button"
                onClick={handleAutoFillReturn}
                className="text-[9px] underline text-amber-300 hover:text-white"
              >
                Auto Samakan
              </button>
            </div>
            <div className="text-sm sm:text-base font-black text-amber-300 font-mono">
              {formatRupiah(returnAmount)}
            </div>
            <div className="text-[10px] text-slate-400 truncate">
              {returnMethod.split(" ")[0]} - {receiptNumber || "Belum ada STS"}
            </div>
          </div>

          {/* Card 5: Rekonsiliasi & Batas Waktu 2 Minggu */}
          <div className="bg-slate-900 border border-slate-700/80 p-3 rounded-xl space-y-1 col-span-2 lg:col-span-1">
            <div className="text-[10px] text-slate-400 uppercase font-bold flex items-center justify-between">
              <span>Status 2 Minggu</span>
              <Clock className="w-3.5 h-3.5 text-amber-400" />
            </div>
            <div className="flex items-center gap-1.5">
              <span className={`text-[10px] px-2 py-0.5 rounded border font-bold ${deadline.badgeClass}`}>
                {deadline.statusText}
              </span>
            </div>
            <div className="text-[10px] font-mono flex justify-between text-slate-400">
              <span>Selisih Rekonsiliasi:</span>
              <span className={`font-bold ${finalDiscrepancy === 0 ? "text-emerald-400" : "text-rose-400"}`}>
                {finalDiscrepancy === 0 ? "Rp 0 (SEIMBANG)" : formatRupiah(finalDiscrepancy)}
              </span>
            </div>
          </div>

        </div>

        {/* Main Content Area */}
        <div className="p-5 sm:p-6 space-y-6 max-h-[68vh] overflow-y-auto">
          
          {/* ========================================================================= */}
          {/* SECTION A: VOUCHER 2 - REALISASI BELANJA EXPENDABLES & OPERASIONAL */}
          {/* ========================================================================= */}
          <div className="space-y-4 bg-slate-950/50 p-4 sm:p-5 rounded-2xl border border-sky-500/20">
            <div className="flex flex-wrap items-center justify-between gap-3 border-b border-slate-800 pb-3">
              <div className="flex items-center gap-2.5">
                <div className="p-2 bg-sky-500/20 text-sky-400 rounded-lg">
                  <Receipt className="w-4 h-4" />
                </div>
                <div>
                  <h3 className="text-sm font-bold text-white flex items-center gap-2">
                    VOUCHER 2: REALISASI BELANJA KAS KECIL & KUITANSI SAH
                    <span className="text-[10px] font-mono bg-sky-500/20 text-sky-300 border border-sky-500/30 px-2 py-0.5 rounded">
                      {umk.realizationVoucher.voucherNumber}
                    </span>
                  </h3>
                  <p className="text-xs text-slate-400">
                    Minimal mencakup 1 mata anggaran Expendables (Bahan Habis Pakai) atau multi rincian pos anggaran operasional GA
                  </p>
                </div>
              </div>

              <div className="flex items-center gap-2">
                <button
                  type="button"
                  onClick={handleAddItem}
                  className="px-3 py-1.5 bg-gradient-to-r from-sky-500 to-blue-600 hover:from-sky-400 hover:to-blue-500 text-slate-950 font-bold text-xs rounded-lg shadow-md flex items-center gap-1.5 transition-all cursor-pointer"
                >
                  <Plus className="w-3.5 h-3.5" />
                  <span>Tambah Baris Belanja</span>
                </button>
              </div>
            </div>

            {/* Expense Items Table */}
            <div className="overflow-x-auto">
              <table className="w-full text-left text-xs border-collapse">
                <thead>
                  <tr className="border-b border-slate-800 text-slate-400 uppercase font-bold text-[10px]">
                    <th className="py-2 px-2 w-8 text-center">#</th>
                    <th className="py-2 px-2 w-28">Tgl Belanja</th>
                    <th className="py-2 px-2 w-48">Mata Anggaran</th>
                    <th className="py-2 px-2">Uraian Transaksi Belanja</th>
                    <th className="py-2 px-2 w-36">Toko / Vendor</th>
                    <th className="py-2 px-2 w-36">No. Kuitansi Sah</th>
                    <th className="py-2 px-2 w-32 text-right">Nominal (Rp)</th>
                    <th className="py-2 px-1 w-8 text-center">Aksi</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-800/60">
                  {expenseItems.map((item, index) => (
                    <tr key={item.id} className="hover:bg-slate-800/30 transition-colors">
                      <td className="py-2.5 px-2 text-center font-mono text-slate-500">
                        {index + 1}
                      </td>

                      {/* Transaction Date */}
                      <td className="py-2.5 px-2">
                        <input
                          type="date"
                          value={item.transactionDate}
                          onChange={(e) => handleItemChange(item.id, "transactionDate", e.target.value)}
                          className="w-full px-2 py-1.5 bg-slate-900 border border-slate-700 rounded text-xs text-white focus:outline-none focus:border-sky-500 font-mono"
                        />
                      </td>

                      {/* Budget Account Selector */}
                      <td className="py-2.5 px-2">
                        <select
                          value={item.budgetCode}
                          onChange={(e) => handleItemChange(item.id, "budgetCode", e.target.value)}
                          className="w-full px-2 py-1.5 bg-slate-900 border border-slate-700 rounded text-xs text-white focus:outline-none focus:border-sky-500 font-mono"
                        >
                          {UMK_BUDGET_ACCOUNTS.map((acct) => (
                            <option key={acct.code} value={acct.code}>
                              {acct.isExpendables ? "[EXP] " : "[OPS] "} {acct.name}
                            </option>
                          ))}
                        </select>
                        <span className={`inline-block text-[9px] font-bold mt-0.5 ${
                          item.isExpendables ? "text-emerald-400" : "text-purple-400"
                        }`}>
                          {item.isExpendables ? "✓ EXPENDABLES (Bahan Habis Pakai)" : "• OPERASIONAL / LAINNYA"}
                        </span>
                      </td>

                      {/* Item Description */}
                      <td className="py-2.5 px-2">
                        <input
                          type="text"
                          required
                          value={item.itemDescription}
                          onChange={(e) => handleItemChange(item.id, "itemDescription", e.target.value)}
                          placeholder="Contoh: Pembelian Kertas HVS 10 Rim, Tinta & Binder"
                          className="w-full px-2.5 py-1.5 bg-slate-900 border border-slate-700 rounded text-xs text-white focus:outline-none focus:border-sky-500"
                        />
                      </td>

                      {/* Vendor Name */}
                      <td className="py-2.5 px-2">
                        <input
                          type="text"
                          required
                          value={item.vendorName}
                          onChange={(e) => handleItemChange(item.id, "vendorName", e.target.value)}
                          placeholder="Nama Toko / Rekanan"
                          className="w-full px-2 py-1.5 bg-slate-900 border border-slate-700 rounded text-xs text-white focus:outline-none focus:border-sky-500"
                        />
                      </td>

                      {/* Receipt Number & Type */}
                      <td className="py-2.5 px-2 space-y-1">
                        <input
                          type="text"
                          required
                          value={item.receiptNumber}
                          onChange={(e) => handleItemChange(item.id, "receiptNumber", e.target.value)}
                          placeholder="No. Kuitansi / Struk"
                          className="w-full px-2 py-1 bg-slate-900 border border-slate-700 rounded text-xs text-white focus:outline-none focus:border-sky-500 font-mono"
                        />
                        <select
                          value={item.receiptType}
                          onChange={(e: any) => handleItemChange(item.id, "receiptType", e.target.value)}
                          className="w-full px-1.5 py-0.5 bg-slate-950 border border-slate-800 rounded text-[10px] text-slate-400 focus:outline-none"
                        >
                          <option value="Struk Kasir Sah / Invoice">Struk Kasir Sah / Invoice</option>
                          <option value="Kuitansi Bermaterai">Kuitansi Bermaterai</option>
                          <option value="Nota Resmi Toko / Vendor">Nota Resmi Toko / Vendor</option>
                          <option value="e-Invoice / Faktur Pajak">e-Invoice / Faktur Pajak</option>
                          <option value="Kuitansi Internal GA">Kuitansi Internal GA</option>
                        </select>
                      </td>

                      {/* Amount */}
                      <td className="py-2.5 px-2 text-right">
                        <input
                          type="number"
                          required
                          min={1}
                          value={item.amount || ""}
                          onChange={(e) => handleItemChange(item.id, "amount", e.target.value)}
                          placeholder="0"
                          className="w-full px-2 py-1.5 bg-slate-900 border border-slate-700 rounded text-xs text-white text-right font-mono font-bold focus:outline-none focus:border-sky-500"
                        />
                        <div className="text-[9px] text-slate-400 font-mono mt-0.5">
                          {formatRupiah(item.amount || 0)}
                        </div>
                      </td>

                      {/* Delete Action */}
                      <td className="py-2.5 px-1 text-center">
                        <button
                          type="button"
                          onClick={() => handleRemoveItem(item.id)}
                          className="p-1 text-rose-400 hover:text-rose-300 hover:bg-rose-900/30 rounded transition-colors"
                          title="Hapus baris"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
                <tfoot>
                  <tr className="border-t-2 border-slate-700 font-bold bg-slate-900/60">
                    <td colSpan={6} className="py-3 px-3 text-right uppercase text-slate-300 text-xs">
                      Total Realisasi Belanja (Voucher 2):
                    </td>
                    <td className="py-3 px-2 text-right font-mono text-sm font-black text-sky-400">
                      {formatRupiah(totalRealized)}
                    </td>
                    <td></td>
                  </tr>
                </tfoot>
              </table>
            </div>

            {/* Realization Notes */}
            <div className="pt-2">
              <label className="text-xs font-bold text-slate-300">
                Catatan Realisasi Belanja Kas Kecil GA (LPJ Voucher 2)
              </label>
              <input
                type="text"
                value={realizationNotes}
                onChange={(e) => setRealizationNotes(e.target.value)}
                placeholder="Catatan tambahan pertanggungjawaban belanja harian..."
                className="w-full px-3 py-1.5 bg-slate-900 border border-slate-700 rounded-lg text-xs text-white mt-1 focus:outline-none focus:border-sky-500"
              />
            </div>
          </div>

          {/* ========================================================================= */}
          {/* SECTION B: VOUCHER 1 - PENGEMBALIAN SISA UMK (RETURN VOUCHER) */}
          {/* ========================================================================= */}
          <div className="space-y-4 bg-slate-950/50 p-4 sm:p-5 rounded-2xl border border-amber-500/20">
            <div className="flex flex-wrap items-center justify-between gap-3 border-b border-slate-800 pb-3">
              <div className="flex items-center gap-2.5">
                <div className="p-2 bg-amber-500/20 text-amber-400 rounded-lg">
                  <ArrowDownLeft className="w-4 h-4" />
                </div>
                <div>
                  <h3 className="text-sm font-bold text-white flex items-center gap-2">
                    VOUCHER 1: PENGEMBALIAN SISA UMK (SETORAN SISA KAS KECIL)
                    <span className="text-[10px] font-mono bg-amber-500/20 text-amber-300 border border-amber-500/30 px-2 py-0.5 rounded">
                      {umk.returnVoucher.voucherNumber}
                    </span>
                  </h3>
                  <p className="text-xs text-slate-400">
                    Mencatat pengembalian sisa dana kas kecil yang tidak terpakai kembali ke Kasir Perbendaharaan Keuangan
                  </p>
                </div>
              </div>

              <div className="flex items-center gap-2">
                <button
                  type="button"
                  onClick={handleAutoFillReturn}
                  className="px-3 py-1 bg-amber-500/20 hover:bg-amber-500/30 border border-amber-500/40 text-amber-300 font-bold text-xs rounded-lg transition-all"
                >
                  Set Sisa Otomatis ({formatRupiah(Math.max(0, calculatedBalanceRemaining))})
                </button>
              </div>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 text-xs">
              <div className="space-y-1">
                <label className="text-xs font-bold text-slate-300">
                  Nominal Sisa Disetor (Rp) <span className="text-rose-400">*</span>
                </label>
                <div className="relative">
                  <span className="absolute left-3 top-2 text-xs font-bold text-slate-400">Rp</span>
                  <input
                    type="number"
                    min={0}
                    value={returnAmount}
                    onChange={(e) => setReturnAmount(Number(e.target.value) || 0)}
                    className="w-full pl-10 pr-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-xs text-white font-mono font-bold focus:outline-none focus:border-amber-500"
                  />
                </div>
                <div className="text-[10px] text-amber-400 font-mono mt-0.5">
                  {formatRupiah(returnAmount)}
                </div>
              </div>

              <div className="space-y-1">
                <label className="text-xs font-bold text-slate-300">
                  Tanggal Pengembalian Kas
                </label>
                <input
                  type="date"
                  value={returnDate}
                  onChange={(e) => setReturnDate(e.target.value)}
                  className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-xs text-white focus:outline-none focus:border-amber-500 font-mono"
                />
              </div>

              <div className="space-y-1">
                <label className="text-xs font-bold text-slate-300">
                  Metode Setoran
                </label>
                <select
                  value={returnMethod}
                  onChange={(e: any) => setReturnMethod(e.target.value)}
                  className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-xs text-white focus:outline-none focus:border-amber-500"
                >
                  <option value="Setor Tunai Kasir Keuangan">Setor Tunai Kasir Keuangan</option>
                  <option value="Transfer Kas Perusahaan">Transfer Kas Perusahaan</option>
                </select>
              </div>

              <div className="space-y-1">
                <label className="text-xs font-bold text-slate-300">
                  Nomor Bukti Setor Kasir (STS)
                </label>
                <input
                  type="text"
                  value={receiptNumber}
                  onChange={(e) => setReceiptNumber(e.target.value)}
                  placeholder="STS-KEU/2026/..."
                  className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-xs text-white font-mono focus:outline-none focus:border-amber-500"
                />
              </div>

              <div className="space-y-1">
                <label className="text-xs font-bold text-slate-300">
                  Penerima Kasir Keuangan
                </label>
                <input
                  type="text"
                  value={receivedByName}
                  onChange={(e) => setReceivedByName(e.target.value)}
                  className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-xs text-white focus:outline-none focus:border-amber-500"
                />
              </div>

              <div className="space-y-1">
                <label className="text-xs font-bold text-slate-300">
                  NIP Kasir Keuangan
                </label>
                <input
                  type="text"
                  value={receivedByNip}
                  onChange={(e) => setReceivedByNip(e.target.value)}
                  className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-xs text-white font-mono focus:outline-none focus:border-amber-500"
                />
              </div>

              <div className="space-y-1 sm:col-span-3">
                <label className="text-xs font-bold text-slate-300">
                  Catatan Pengembalian Sisa Kas (Voucher 1)
                </label>
                <input
                  type="text"
                  value={returnNotes}
                  onChange={(e) => setReturnNotes(e.target.value)}
                  placeholder="Contoh: Sisa kas kecil telah disetor tunai ke kasir pusat dan diverifikasi."
                  className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-xs text-white focus:outline-none focus:border-amber-500"
                />
              </div>
            </div>
          </div>

          {/* ========================================================================= */}
          {/* SECTION C: REKONSILIASI & BALANCE VERIFICATION */}
          {/* ========================================================================= */}
          <div className="bg-slate-900 border border-slate-700 p-4 rounded-xl space-y-3">
            <div className="flex items-center justify-between border-b border-slate-800 pb-2">
              <span className="text-xs font-bold uppercase tracking-wider text-slate-300 flex items-center gap-2">
                <Calculator className="w-4 h-4 text-emerald-400" />
                <span>Rekonsiliasi Lengkap UMK: Dana Awal vs (Voucher 2 + Voucher 1)</span>
              </span>
              <span className="text-xs font-mono font-bold">
                {finalDiscrepancy === 0 ? (
                  <span className="text-emerald-400 bg-emerald-500/20 border border-emerald-500/40 px-2 py-0.5 rounded">
                    ✓ REKONSILIASI SEIMBANG (NIHIL / KLIR)
                  </span>
                ) : (
                  <span className="text-rose-400 bg-rose-500/20 border border-rose-500/40 px-2 py-0.5 rounded">
                    ⚠ SELISIH {formatRupiah(Math.abs(finalDiscrepancy))}
                  </span>
                )}
              </span>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 text-xs">
              <div className="p-3 bg-slate-950 rounded-lg space-y-1">
                <div className="text-slate-400">A. Dana Awal UMK:</div>
                <div className="text-sm font-mono font-bold text-white">{formatRupiah(initialAmount)}</div>
              </div>
              <div className="p-3 bg-slate-950 rounded-lg space-y-1">
                <div className="text-slate-400">B. Realisasi + Pengembalian (V2 + V1):</div>
                <div className="text-sm font-mono font-bold text-sky-300">
                  {formatRupiah(totalRealized)} + {formatRupiah(returnAmount)} = {formatRupiah(totalAccounted)}
                </div>
              </div>
              <div className="p-3 bg-slate-950 rounded-lg space-y-1">
                <div className="text-slate-400">C. Selisih Rekonsiliasi (A - B):</div>
                <div className={`text-sm font-mono font-bold ${
                  finalDiscrepancy === 0 ? "text-emerald-400" : "text-rose-400"
                }`}>
                  {formatRupiah(finalDiscrepancy)}
                </div>
              </div>
            </div>
          </div>

        </div>

        {/* Footer Actions */}
        <div className="bg-slate-950 p-4 border-t border-slate-800 flex flex-wrap items-center justify-between gap-3">
          <button
            type="button"
            onClick={onClose}
            className="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-bold rounded-xl transition-all"
          >
            Tutup
          </button>

          <div className="flex items-center gap-2">
            <button
              type="button"
              onClick={() => handleSave(false)}
              className="px-4 py-2 bg-slate-800 hover:bg-slate-700 border border-slate-600 text-slate-200 text-xs font-bold rounded-xl transition-all cursor-pointer"
            >
              Simpan Draft Realisasi
            </button>

            <button
              type="button"
              onClick={() => handleSave(true)}
              className="px-6 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/20 flex items-center gap-2 transition-all cursor-pointer"
            >
              <CheckCircle2 className="w-4 h-4" />
              <span>Sahkan & Laporkan LPJ 2 Voucher ke Keuangan</span>
            </button>
          </div>
        </div>

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

export default UmkSettlementModal;
