/**
 * DaftarInvoice.jsx — Halaman daftar seluruh invoice PT. Sarana Gemilang
 *
 * Revisi:
 *   - Tombol Eye (print preview) → diganti FileSearch (buka Detail Data)
 *   - Print Invoice tetap bisa diakses dari tombol "Print Invoice" di dalam
 *     InvoiceDataDetailModal, yang akan membuka InvoicePreviewModal
 *   - Tambah state detailInv + mounting InvoiceDataDetailModal
 *   - Hapus duplicate import lucide-react
 */
import { useState, useMemo } from 'react'
import { useApp } from '../context/AppContext'
import { formatRupiah } from '../utils/formatRupiah'
import { useDebounce } from '../hooks/useDebounce'
import { formatTanggalIndo, getKategoriTab } from '../utils/generateNomorKW'
import { exportInvoiceMultiTab } from '../utils/exportExcel'
import PageHeader from '../components/PageHeader'
import InvoicePreviewModal from '../components/InvoicePreviewModal'
import InvoiceDataDetailModal from '../components/InvoiceDataDetailModal'
import ConfirmDialog from '../components/ConfirmDialog'
import ExtendModal from '../components/ExtendModal'
import {
  FileText, Trash2, FileSearch, Search,
  Filter, TrendingUp, Package, ChevronDown,
  Calendar, X, AlertCircle, Download,
  ChevronLeft, ChevronRight, CheckCircle2,
  Clock,
} from 'lucide-react'

const PER_PAGE = 10

const TABS = [
  { key: 'BTD',         label: 'BTD — BCF 1.5',  color: '#f43f5e', bg: '#fff1f2', border: '#fecdd3' },
  { key: 'BDN',         label: 'BDN — KEP BDN',  color: '#f97316', bg: '#fff7ed', border: '#fed7aa' },
  { key: 'Gudang Umum', label: 'Gudang Umum',     color: '#10b981', bg: '#f0fdf4', border: '#bbf7d0' },
]

const JENIS_COLOR = {
  // Legacy label format
  'FCL TPP — BTD':         { bg: '#fff1f2', text: '#be123c', dot: '#f43f5e' },
  'FCL TPP — BDN':         { bg: '#fff7ed', text: '#c2410c', dot: '#f97316' },
  'LCL TPP — BTD':         { bg: '#faf5ff', text: '#7e22ce', dot: '#a855f7' },
  'LCL TPP — BDN':         { bg: '#fdf4ff', text: '#86198f', dot: '#d946ef' },
  'Gudang Umum FCL':       { bg: '#f0fdf4', text: '#166534', dot: '#22c55e' },
  'Gudang Umum LCL':       { bg: '#ecfdf5', text: '#065f46', dot: '#10b981' },
  'Full Container Ekspor': { bg: '#e0f2fe', text: '#0369a1', dot: '#0ea5e9' },
  'Full Container Impor':  { bg: '#fef9c3', text: '#92400e', dot: '#f59e0b' },
  'LCL':                   { bg: '#f5f3ff', text: '#5b21b6', dot: '#8b5cf6' },
  // Prisma enum format
  FCL_TPP_BTD: { bg: '#fff1f2', text: '#be123c', dot: '#f43f5e' },
  FCL_TPP_BDN: { bg: '#fff7ed', text: '#c2410c', dot: '#f97316' },
  LCL_TPP_BTD: { bg: '#faf5ff', text: '#7e22ce', dot: '#a855f7' },
  LCL_TPP_BDN: { bg: '#fdf4ff', text: '#86198f', dot: '#d946ef' },
  GUDANG_FCL:  { bg: '#f0fdf4', text: '#166534', dot: '#22c55e' },
  GUDANG_LCL:  { bg: '#ecfdf5', text: '#065f46', dot: '#10b981' },
  FULL_EKSPOR: { bg: '#e0f2fe', text: '#0369a1', dot: '#0ea5e9' },
  FULL_IMPOR:  { bg: '#fef9c3', text: '#92400e', dot: '#f59e0b' },
}

const JENIS_LABEL = {
  FCL_TPP_BTD: 'FCL TPP — BTD',
  FCL_TPP_BDN: 'FCL TPP — BDN',
  LCL_TPP_BTD: 'LCL TPP — BTD',
  LCL_TPP_BDN: 'LCL TPP — BDN',
  GUDANG_FCL:  'Gudang Umum FCL',
  GUDANG_LCL:  'Gudang Umum LCL',
  FULL_EKSPOR: 'Full Container Ekspor',
  FULL_IMPOR:  'Full Container Impor',
}

function jenisLabel(jenis = '') {
  return JENIS_LABEL[jenis] || jenis
}

function getJenisColor(jenis = '') {
  if (JENIS_COLOR[jenis]) return JENIS_COLOR[jenis]
  const j = jenis.toLowerCase()
  if (j.includes('fcl tpp') && j.includes('btd')) return JENIS_COLOR['FCL TPP — BTD']
  if (j.includes('fcl tpp') && j.includes('bdn')) return JENIS_COLOR['FCL TPP — BDN']
  if (j.includes('lcl tpp') && j.includes('btd')) return JENIS_COLOR['LCL TPP — BTD']
  if (j.includes('lcl tpp') && j.includes('bdn')) return JENIS_COLOR['LCL TPP — BDN']
  if (j.includes('gudang')  && j.includes('fcl')) return JENIS_COLOR['Gudang Umum FCL']
  if (j.includes('gudang')  && j.includes('lcl')) return JENIS_COLOR['Gudang Umum LCL']
  if (j.includes('full')    && j.includes('ekspor')) return JENIS_COLOR['Full Container Ekspor']
  if (j.includes('full')    && j.includes('impor'))  return JENIS_COLOR['Full Container Impor']
  if (j.includes('lcl')) return JENIS_COLOR['LCL']
  return { bg: '#f1f5f9', text: '#475569', dot: '#94a3b8' }
}

function JenisBadge({ jenis }) {
  const label = jenisLabel(jenis)
  const c = getJenisColor(jenis)
  return (
    <span
      className="inline-flex items-center gap-1.5 text-[11px] font-bold px-2.5 py-1 rounded-full whitespace-nowrap"
      style={{ background: c.bg, color: c.text }}
    >
      <span className="w-1.5 h-1.5 rounded-full shrink-0" style={{ background: c.dot }} />
      {label}
    </span>
  )
}

// ── Tombol aksi dalam tabel — style konsisten ────────────────────────────────
function ActionBtn({ icon, title, onClick, border, bg, color, hoverBg, disabled = false }) {
  return (
    <button
      onClick={onClick}
      title={title}
      disabled={disabled}
      style={{
        width: 28, height: 28,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        borderRadius: 7, border: `1px solid ${border}`,
        background: bg, color,
        cursor: disabled ? 'default' : 'pointer',
        flexShrink: 0, transition: 'background 0.1s',
        opacity: disabled ? 0.45 : 1,
      }}
      onMouseEnter={e => !disabled && (e.currentTarget.style.background = hoverBg)}
      onMouseLeave={e => !disabled && (e.currentTarget.style.background = bg)}
    >
      {icon}
    </button>
  )
}

// ════════════════════════════════════════════════════════════════════════════════
// MAIN COMPONENT
// ════════════════════════════════════════════════════════════════════════════════
export default function DaftarInvoice() {
  const { invoiceList, hapusInvoice, lunasInvoice, showToast } = useApp()

  // ── Filter & navigasi ──
  const [activeTab,      setActiveTab]      = useState('BTD')
  const [searchInput, setSearchInput] = useState('')
  const search = useDebounce(searchInput, 300)
  const [filterBulan,    setFilterBulan]    = useState('')
  const [filterMinTotal, setFilterMinTotal] = useState('')
  const [filterMaxTotal, setFilterMaxTotal] = useState('')
  const [filterTglDari,  setFilterTglDari]  = useState('')
  const [filterTglSampai,setFilterTglSampai]= useState('')
  const [showFilterAdv,  setShowFilterAdv]  = useState(false)
  const [page,           setPage]           = useState(1)

  // ── Modal state ──
  const [detailInv,      setDetailInv]      = useState(null)  // InvoiceDataDetailModal
  const [previewInv,     setPreviewInv]     = useState(null)  // InvoicePreviewModal (print)
  const [deleteConfirm,  setDeleteConfirm]  = useState(null)
  const [alasanHapus,    setAlasanHapus]    = useState('')
  const [lunasConfirm,   setLunasConfirm]   = useState(null)
  const [showExtendModal,setShowExtendModal] = useState(false)

  // ── Grouping invoice per tab ──────────────────────────────────────────────
  const grouped = useMemo(() => {
    const out = { BTD: [], BDN: [], 'Gudang Umum': [] }
    invoiceList.forEach(inv => {
      const tab = getKategoriTab(inv.jenisLayanan || '')
      if (out[tab]) out[tab].push(inv)
      else out['BTD'].push(inv)
    })
    return out
  }, [invoiceList])

  // ── Filter dalam tab aktif ────────────────────────────────────────────────
  const tabData = useMemo(() => (grouped[activeTab] || []).filter(inv => {
    const gt = inv.grandTotal || 0
    const q  = search.toLowerCase()
    return (
      (!search         || inv.nomorKW?.toLowerCase().includes(q) || inv.consignee?.toLowerCase().includes(q)) &&
      (!filterBulan    || inv.tanggalInvoice?.startsWith(filterBulan)) &&
      (!filterMinTotal || gt >= parseFloat(filterMinTotal) * 1e6) &&
      (!filterMaxTotal || gt <= parseFloat(filterMaxTotal) * 1e6) &&
      (!filterTglDari  || inv.tanggalInvoice >= filterTglDari) &&
      (!filterTglSampai|| inv.tanggalInvoice <= filterTglSampai)
    )
  }), [grouped, activeTab, search, filterBulan, filterMinTotal, filterMaxTotal, filterTglDari, filterTglSampai])

  const totalPages = Math.max(1, Math.ceil(tabData.length / PER_PAGE))
  const safePage   = Math.min(page, totalPages)
  const paginated  = tabData.slice((safePage - 1) * PER_PAGE, safePage * PER_PAGE)

  const changeTab    = (key) => { setActiveTab(key); setPage(1); setSearch('') }
  const resetFilters = () => {
    setSearchInput(''); setFilterBulan(''); setFilterTglDari(''); setFilterTglSampai('')
    setFilterMinTotal(''); setFilterMaxTotal(''); setPage(1)
  }
  const hasFilter = search || filterBulan || filterTglDari || filterTglSampai || filterMinTotal || filterMaxTotal

  const totalPendapatan = tabData.reduce((s, inv) => s + (inv.grandTotal || 0), 0)

  const bulanOptions = useMemo(() => {
    const set = new Set((grouped[activeTab] || []).map(inv => inv.tanggalInvoice?.slice(0, 7)).filter(Boolean))
    const B   = ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des']
    return [...set].sort().reverse().map(ym => {
      const [y, m] = ym.split('-')
      return { value: ym, label: `${B[parseInt(m) - 1]} ${y}` }
    })
  }, [grouped, activeTab])

  const tabsWithCount = TABS.map(t => ({ ...t, count: grouped[t.key]?.length || 0 }))

  // ── Handler Lunas ──────────────────────────────────────────────────────────
  const handleLunas = async (inv) => {
    await lunasInvoice(inv.id)
    showToast(`Invoice ${inv.nomorKW} dikonfirmasi LUNAS ✓`, 'sukses')
    setLunasConfirm(null)
  }

  // ── Handler Hapus ──────────────────────────────────────────────────────────
  const handleHapus = async () => {
    if (!deleteConfirm) return
    const alasan = alasanHapus.trim() || 'Dihapus oleh admin'
    await hapusInvoice(deleteConfirm.id, alasan)
    showToast(`Invoice ${deleteConfirm.nomorKW} berhasil dihapus.`, 'peringatan')
    setDeleteConfirm(null)
    setAlasanHapus('')
  }

  // ── Handler: dari Detail Modal → buka Print Preview ───────────────────────
  const handlePrintFromDetail = (inv) => {
    setDetailInv(null)         // tutup detail modal dulu
    setTimeout(() => setPreviewInv(inv), 50) // buka print setelah animasi close
  }

  return (
    <div className="flex-1 flex flex-col">

      {/* ── Page Header ── */}
      <PageHeader
        title="Daftar Invoice"
        subtitle={`${invoiceList.length} invoice tersimpan`}
        actions={
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <button
              onClick={() => setShowExtendModal(true)}
              style={{
                display: 'flex', alignItems: 'center', gap: 6,
                height: 36, padding: '0 16px', borderRadius: 8,
                border: '1.5px solid #f59e0b', background: '#fffbeb',
                color: '#92400e', fontSize: 13, fontWeight: 700,
                cursor: 'pointer', fontFamily: 'inherit',
                transition: 'all 0.15s', whiteSpace: 'nowrap',
              }}
              onMouseEnter={e => { e.currentTarget.style.background = '#fef3c7'; e.currentTarget.style.borderColor = '#d97706' }}
              onMouseLeave={e => { e.currentTarget.style.background = '#fffbeb'; e.currentTarget.style.borderColor = '#f59e0b' }}
            >
              <Clock size={14} /> Extend Storage
            </button>
            <button
  onClick={() => exportInvoiceMultiTab({
    groupedInvoices: grouped,           // ← kirim semua 3 tab sekaligus
    bulan: new Date().getMonth() + 1,
    tahun: new Date().getFullYear(),
  })}
  className="flex items-center gap-2 h-9 px-4 rounded-lg border border-emerald-300 bg-emerald-50 text-emerald-700 text-[13px] font-semibold hover:bg-emerald-100 transition-colors"
            >
              <Download size={14} /> Export Semua ({invoiceList.length})
            </button>
          </div>
        }
      />

      <div className="px-8 py-6 flex flex-col gap-5">

        {/* ── Stats cards ── */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 12 }}>
          {[
            { label: `Invoice ${activeTab}`, value: grouped[activeTab]?.length || 0, sub: `${tabData.length} sesuai filter`, color: '#0ea5e9', Icon: FileText  },
            { label: 'Total Pendapatan',     value: formatRupiah(totalPendapatan),   sub: 'Tab aktif · sesuai filter',        color: '#10b981', Icon: TrendingUp },
            { label: 'Total Semua Invoice',  value: invoiceList.length,              sub: '3 kategori tersedia',              color: '#8b5cf6', Icon: Package    },
          ].map(({ label, value, sub, color, Icon }) => (
            <div key={label} style={{ background: 'white', borderRadius: 12, border: '1px solid #e2e8f0', padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ width: 40, height: 40, borderRadius: 10, background: color + '18', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon size={18} color={color} />
              </div>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 11, color: '#94a3b8', fontWeight: 600, marginBottom: 3 }}>{label}</div>
                <div style={{ fontSize: 16, fontWeight: 800, color: '#0f172a', lineHeight: 1.2 }}>{value}</div>
                {sub && <div style={{ fontSize: 11, color: '#94a3b8', marginTop: 3 }}>{sub}</div>}
              </div>
            </div>
          ))}
        </div>

        {/* ── Main card ── */}
        <div style={{ background: 'white', borderRadius: 14, border: '1px solid #e2e8f0', boxShadow: '0 1px 3px rgba(0,0,0,0.06)', overflow: 'hidden' }}>

          {/* Sub-tab bar */}
          <div style={{ display: 'flex', borderBottom: '1.5px solid #e2e8f0', paddingLeft: 20, paddingRight: 20, background: 'white', borderRadius: '14px 14px 0 0' }}>
            {tabsWithCount.map(tab => {
              const active = activeTab === tab.key
              return (
                <button
                  key={tab.key}
                  onClick={() => changeTab(tab.key)}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 8,
                    padding: '14px 20px 13px',
                    fontSize: 13.5, fontWeight: active ? 700 : 500,
                    color: active ? tab.color : '#94a3b8',
                    background: 'transparent', border: 'none',
                    borderBottom: active ? `2.5px solid ${tab.color}` : '2.5px solid transparent',
                    cursor: 'pointer', fontFamily: 'inherit',
                    marginBottom: -1.5, transition: 'color 0.15s', whiteSpace: 'nowrap',
                  }}
                  onMouseEnter={e => { if (!active) e.currentTarget.style.color = '#475569' }}
                  onMouseLeave={e => { if (!active) e.currentTarget.style.color = '#94a3b8' }}
                >
                  {tab.label}
                  <span style={{
                    fontSize: 11, fontWeight: 700, padding: '2px 7px', borderRadius: 99,
                    background: active ? tab.color : '#f1f5f9',
                    color: active ? 'white' : '#64748b',
                    minWidth: 20, textAlign: 'center', lineHeight: 1.6,
                  }}>
                    {tab.count}
                  </span>
                </button>
              )
            })}
          </div>

          {/* Filter bar */}
          <div className="flex flex-wrap items-center gap-2 px-4 py-3 border-b border-slate-100">
            <div className="relative flex-1 min-w-[180px]">
              <Search size={13} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none" />
              <input
                value={search}
                onChange={e => { setSearchInput(e.target.value); setPage(1) }}
                placeholder="Cari nomor KW atau consignee..."
                className="w-full h-9 pl-8 pr-3 rounded-lg border border-slate-200 text-[12.5px] outline-none focus:border-sky-400 transition-colors"
              />
            </div>
            <div className="relative shrink-0">
              <Calendar size={12} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none" />
              <select
                value={filterBulan}
                onChange={e => { setFilterBulan(e.target.value); setPage(1) }}
                className="h-9 pl-7 pr-7 rounded-lg border border-slate-200 text-[12.5px] outline-none bg-white appearance-none cursor-pointer focus:border-sky-400 min-w-[120px]"
              >
                <option value="">Semua Bulan</option>
                {bulanOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
              </select>
              <ChevronDown size={12} className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none" />
            </div>
            <button
              onClick={() => setShowFilterAdv(p => !p)}
              className={`flex items-center gap-1.5 h-9 px-3 rounded-lg border text-[12px] font-semibold transition-colors shrink-0 ${showFilterAdv ? 'border-sky-300 bg-sky-50 text-sky-700' : 'border-slate-200 text-slate-500 hover:bg-slate-50'}`}
            >
              <Filter size={12} /> Filter Lanjut
            </button>
            {hasFilter && (
              <button
                onClick={resetFilters}
                className="flex items-center gap-1.5 h-9 px-3 rounded-lg border border-red-200 bg-red-50 text-red-500 text-[12px] font-semibold hover:bg-red-100 transition-colors shrink-0"
              >
                <X size={12} /> Reset
              </button>
            )}
          </div>

          {/* Filter lanjutan */}
          {showFilterAdv && (
            <div className="flex flex-wrap items-end gap-3 px-4 py-3 bg-sky-50 border-b border-sky-100">
              <div className="text-[11px] font-bold text-sky-700 w-full -mb-1">Filter Lanjutan</div>
              {[
                ['Tanggal Dari',  filterTglDari,  setFilterTglDari],
                ['Tanggal Sampai',filterTglSampai,setFilterTglSampai],
              ].map(([lbl, val, set]) => (
                <div key={lbl}>
                  <div className="text-[11px] font-semibold text-slate-500 mb-1">{lbl}</div>
                  <input type="date" value={val} onChange={e => { set(e.target.value); setPage(1) }}
                    className="h-8 px-2.5 rounded-lg border border-slate-200 text-[12.5px] outline-none focus:border-sky-400 bg-white" />
                </div>
              ))}
              {[
                ['Min Total (Juta Rp)', filterMinTotal, setFilterMinTotal],
                ['Max Total (Juta Rp)', filterMaxTotal, setFilterMaxTotal],
              ].map(([lbl, val, set]) => (
                <div key={lbl}>
                  <div className="text-[11px] font-semibold text-slate-500 mb-1">{lbl}</div>
                  <input type="number" value={val} onChange={e => { set(e.target.value); setPage(1) }} placeholder="Cth: 5" min={0}
                    className="w-24 h-8 px-2.5 rounded-lg border border-slate-200 text-[12.5px] outline-none focus:border-sky-400 bg-white" />
                </div>
              ))}
              <div className="ml-auto text-[12px] font-bold text-sky-700 self-end pb-1">✓ {tabData.length} ditemukan</div>
            </div>
          )}

          {/* ── Tabel / Empty state ── */}
          {tabData.length === 0 ? (
            <div className="py-16 text-center">
              <AlertCircle size={32} className="text-slate-200 mx-auto mb-3" />
              <div className="text-[13.5px] font-bold text-slate-400">
                {(grouped[activeTab]?.length || 0) === 0
                  ? `Belum ada invoice ${activeTab}`
                  : 'Tidak ada yang cocok dengan filter'}
              </div>
              <div className="text-[12px] text-slate-400 mt-1">
                {(grouped[activeTab]?.length || 0) === 0
                  ? 'Terbitkan invoice dari menu TPP atau Gudang Umum.'
                  : 'Coba reset filter untuk melihat semua invoice.'}
              </div>
            </div>
          ) : (
            <>
              <div className="overflow-x-auto">
                <table style={{ width: '100%', minWidth: 820, borderCollapse: 'collapse', tableLayout: 'fixed' }}>
                  <colgroup>
                    <col style={{ width: 'auto' }} />
                    <col style={{ width: 195 }} />
                    <col style={{ width: 118 }} />
                    <col style={{ width: 68 }} />
                    <col style={{ width: 88 }} />
                    <col style={{ width: 158 }} />
                    <col style={{ width: 106 }} />
                  </colgroup>
                  <thead>
                    <tr style={{ background: '#f8fafc', borderBottom: '1.5px solid #e2e8f0' }}>
                      {[
                        ['Nomor KW / Consignee', 'left',   20],
                        ['Jenis Layanan',         'left',   12],
                        ['Tanggal',               'left',   12],
                        ['Unit',                  'center', 12],
                        ['Status',                'center',  8],
                        ['Grand Total',           'right',  12],
                        ['Aksi',                  'center', 16],
                      ].map(([h, align, px]) => (
                        <th key={h} style={{
                          textAlign: align, fontSize: 10.5, fontWeight: 700,
                          color: '#94a3b8', textTransform: 'uppercase', letterSpacing: '0.05em',
                          padding: `10px ${px}px`, whiteSpace: 'nowrap',
                        }}>
                          {h}
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {paginated.map((inv, idx) => {
                      const isLunas = inv.statusPembayaran === 'LUNAS'
                      const isExtend = inv.isExtend || inv.detail?.isExtend

                      // Badge BELUM LUNAS: tampil untuk semua invoice yang belum lunas
                      const isOverstay = !isLunas

                      const rowBg = isLunas
                        ? '#f0fdf4'
                        : isOverstay
                          ? '#fff1f2'
                          : isExtend
                            ? '#fffbeb'
                            : 'transparent'

                      const rowBgHover = isLunas
                        ? '#dcfce7'
                        : isOverstay
                          ? '#ffe4e6'
                          : isExtend
                            ? '#fef3c7'
                            : '#f8fafc'

                      return (
                        <tr
                          key={inv.id}
                          style={{ borderBottom: idx === paginated.length - 1 ? 'none' : '1px solid #f1f5f9', transition: 'background 0.1s', background: rowBg }}
                          onMouseEnter={e => e.currentTarget.style.background = rowBgHover}
                          onMouseLeave={e => e.currentTarget.style.background = rowBg}
                        >
                          {/* Nomor KW + Consignee */}
                          <td style={{ padding: '12px 20px' }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                              {isExtend && (
                                <span style={{ fontSize: 9, fontWeight: 800, padding: '2px 6px', borderRadius: 4, background: '#fef3c7', color: '#92400e', flexShrink: 0 }}>
                                  EXT
                                </span>
                              )}
                              {isOverstay && (
                                <span
                                  title="Invoice ini belum lunas — segera lakukan penagihan"
                                  style={{ fontSize: 9, fontWeight: 800, padding: '2px 6px', borderRadius: 4, background: '#fee2e2', color: '#991b1b', flexShrink: 0 }}
                                >
                                  ⚠ BELUM LUNAS
                                </span>
                              )}
                              <div>
                                <div style={{ fontSize: 13, fontWeight: 700, color: '#0f172a', marginBottom: 2 }}>
                                  {inv.nomorKW}
                                </div>
                                <div style={{ fontSize: 11.5, color: '#64748b', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                  {isExtend && inv.detail?.parentNomorKW && (
                                    <span style={{ color: '#92400e', fontWeight: 600 }}>↳ {inv.detail.parentNomorKW} · </span>
                                  )}
                                  {inv.consignee}
                                </div>
                              </div>
                            </div>
                          </td>

                          {/* Jenis layanan badge */}
                          <td style={{ padding: '12px 12px' }}>
                            <JenisBadge jenis={inv.jenisLayanan} />
                          </td>

                          {/* Tanggal */}
                          <td style={{ padding: '12px 12px', fontSize: 12.5, color: '#64748b', whiteSpace: 'nowrap' }}>
                            {inv.tanggalInvoice ? formatTanggalIndo(inv.tanggalInvoice) : '—'}
                          </td>

                          {/* Unit/Container — baca dari detail.jumlahContainer (fix bug) */}
                          <td style={{ padding: '12px 12px', textAlign: 'center', fontSize: 12.5, color: '#64748b' }}>
                            {inv.detail?.jumlahContainer || inv.jumlahContainer || '—'}
                          </td>

                          {/* Status pembayaran */}
                          <td style={{ padding: '12px 8px', textAlign: 'center' }}>
                            <span style={{
                              display: 'inline-flex', alignItems: 'center', gap: 4,
                              fontSize: 10.5, fontWeight: 700, padding: '3px 9px', borderRadius: 20,
                              background: isLunas ? '#f0fdf4' : '#fff7ed',
                              color:      isLunas ? '#166534' : '#c2410c',
                            }}>
                              <span style={{ width: 5, height: 5, borderRadius: '50%', background: isLunas ? '#22c55e' : '#f97316', flexShrink: 0 }} />
                              {isLunas ? 'Lunas' : 'Terbit'}
                            </span>
                          </td>

                          {/* Grand Total */}
                          <td style={{ padding: '12px 12px', textAlign: 'right', fontSize: 13, fontWeight: 700, color: '#0f172a', whiteSpace: 'nowrap' }}>
                            {formatRupiah(inv.grandTotal)}
                          </td>

                          {/* ── AKSI: FileSearch | CheckCircle2 | Trash2 ── */}
                          <td style={{ padding: '12px 16px' }}>
                            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5 }}>

                              {/* 1. Detail Data (menggantikan Eye print preview) */}
                              <ActionBtn
                                icon={<FileSearch size={13} />}
                                title="Lihat Detail Data Invoice"
                                onClick={() => setDetailInv(inv)}
                                border="#bfdbfe" bg="#eff6ff" color="#1d4ed8" hoverBg="#dbeafe"
                              />

                              {/* 2. Konfirmasi Lunas */}
                              <ActionBtn
                                icon={<CheckCircle2 size={13} />}
                                title={isLunas ? 'Sudah Lunas' : 'Konfirmasi Lunas'}
                                onClick={() => !isLunas && setLunasConfirm(inv)}
                                border={isLunas ? '#bbf7d0' : '#d1fae5'}
                                bg={isLunas ? '#f0fdf4' : '#ecfdf5'}
                                color={isLunas ? '#16a34a' : '#059669'}
                                hoverBg={isLunas ? '#dcfce7' : '#d1fae5'}
                                disabled={isLunas}
                              />

                              {/* 3. Hapus */}
                              <ActionBtn
                                icon={<Trash2 size={13} />}
                                title="Hapus Invoice"
                                onClick={() => setDeleteConfirm(inv)}
                                border="#fecaca" bg="#fff5f5" color="#ef4444" hoverBg="#fee2e2"
                              />

                            </div>
                          </td>
                        </tr>
                      )
                    })}
                  </tbody>
                  <tfoot>
                    <tr style={{ background: '#0f172a' }}>
                      <td colSpan={4} style={{ padding: '11px 20px', fontSize: 11.5, fontWeight: 600, color: 'rgba(255,255,255,0.45)' }}>
                        Total {tabData.length} invoice · Halaman {safePage}/{totalPages}
                      </td>
                      <td />
                      <td style={{ padding: '11px 12px', textAlign: 'right', fontSize: 13.5, fontWeight: 800, color: '#4ade80', whiteSpace: 'nowrap' }}>
                        {formatRupiah(totalPendapatan)}
                      </td>
                      <td />
                    </tr>
                  </tfoot>
                </table>
              </div>

              {/* Pagination */}
              {totalPages > 1 && (
                <div className="flex items-center justify-between px-5 py-3 border-t border-slate-100">
                  <div className="text-[12px] text-slate-500">
                    Menampilkan{' '}
                    <span className="font-semibold text-slate-700">{(safePage - 1) * PER_PAGE + 1}–{Math.min(safePage * PER_PAGE, tabData.length)}</span>
                    {' '}dari{' '}
                    <span className="font-semibold text-slate-700">{tabData.length}</span>
                  </div>
                  <div className="flex items-center gap-1">
                    <button
                      onClick={() => setPage(p => Math.max(1, p - 1))}
                      disabled={safePage === 1}
                      className="w-8 h-8 flex items-center justify-center rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-50 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
                    >
                      <ChevronLeft size={14} />
                    </button>
                    {Array.from({ length: totalPages }, (_, i) => i + 1)
                      .filter(p => p === 1 || p === totalPages || Math.abs(p - safePage) <= 1)
                      .reduce((acc, p, i, arr) => {
                        if (i > 0 && arr[i - 1] !== p - 1) acc.push('...')
                        acc.push(p)
                        return acc
                      }, [])
                      .map((item, i) => item === '...' ? (
                        <span key={`d${i}`} className="w-8 text-center text-[12px] text-slate-400">…</span>
                      ) : (
                        <button
                          key={item}
                          onClick={() => setPage(item)}
                          className={`w-8 h-8 rounded-lg text-[12.5px] font-semibold transition-colors border ${safePage === item ? 'bg-slate-900 text-white border-slate-900' : 'border-slate-200 text-slate-600 hover:bg-slate-50'}`}
                        >
                          {item}
                        </button>
                      ))
                    }
                    <button
                      onClick={() => setPage(p => Math.min(totalPages, p + 1))}
                      disabled={safePage === totalPages}
                      className="w-8 h-8 flex items-center justify-center rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-50 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
                    >
                      <ChevronRight size={14} />
                    </button>
                  </div>
                </div>
              )}
            </>
          )}
        </div>{/* end main card */}
      </div>{/* end px-8 py-6 */}

      {/* ══ MODALS ═══════════════════════════════════════════════════════════════ */}

      {/* Detail Data Invoice — drawer kanan */}
      {detailInv && (
        <InvoiceDataDetailModal
          invoice={detailInv}
          onClose={() => setDetailInv(null)}
          onPrint={() => handlePrintFromDetail(detailInv)}
        />
      )}

      {/* Print Preview A4 — full-screen */}
      {previewInv && (
        <InvoicePreviewModal
          invoice={previewInv}
          onClose={() => setPreviewInv(null)}
        />
      )}

      {/* Extend Storage */}
      {showExtendModal && <ExtendModal onClose={() => setShowExtendModal(false)} />}

      {/* Konfirmasi Lunas */}
      {lunasConfirm && (
        <div
          style={{ position: 'fixed', inset: 0, zIndex: 250, background: 'rgba(10,22,40,0.7)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}
          onClick={() => setLunasConfirm(null)}
        >
          <div
            style={{ background: 'white', borderRadius: 16, padding: 28, maxWidth: 400, width: '100%', boxShadow: '0 20px 60px rgba(0,0,0,0.3)', animation: 'slideUpModal 0.2s ease' }}
            onClick={e => e.stopPropagation()}
          >
            <div style={{ textAlign: 'center', marginBottom: 20 }}>
              <div style={{ width: 56, height: 56, borderRadius: '50%', background: '#f0fdf4', border: '3px solid #bbf7d0', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 12px' }}>
                <CheckCircle2 size={28} color="#16a34a" />
              </div>
              <div style={{ fontSize: 17, fontWeight: 800, color: '#0f172a' }}>Konfirmasi Pembayaran Lunas</div>
              <div style={{ fontSize: 12.5, color: '#64748b', marginTop: 6, lineHeight: 1.6 }}>
                Apakah invoice berikut sudah dibayar lunas oleh importir?
              </div>
            </div>
            <div style={{ background: '#f8fafc', borderRadius: 10, padding: '12px 14px', marginBottom: 20, border: '1px solid #e2e8f0' }}>
              <div style={{ fontFamily: 'monospace', fontSize: 14, fontWeight: 700, color: '#1d4ed8', marginBottom: 4 }}>{lunasConfirm.nomorKW}</div>
              <div style={{ fontSize: 12.5, color: '#64748b', marginBottom: 8 }}>{lunasConfirm.consignee}</div>
              <div style={{ fontSize: 15, fontWeight: 800, color: '#0f172a' }}>{formatRupiah(lunasConfirm.grandTotal)}</div>
            </div>
            <div style={{ display: 'flex', gap: 10 }}>
              <button
                onClick={() => setLunasConfirm(null)}
                style={{ flex: 1, height: 40, borderRadius: 9, border: '1px solid #e2e8f0', background: 'white', color: '#64748b', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}
              >
                Batal
              </button>
              <button
                onClick={() => handleLunas(lunasConfirm)}
                style={{ flex: 2, height: 40, borderRadius: 9, border: 'none', background: 'linear-gradient(135deg,#059669,#047857)', color: 'white', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, boxShadow: '0 2px 10px rgba(5,150,105,0.25)' }}
              >
                <CheckCircle2 size={15} /> Konfirmasi Lunas
              </button>
            </div>
          </div>
          <style>{`@keyframes slideUpModal { from{opacity:0;transform:translateY(12px)} to{opacity:1;transform:translateY(0)} }`}</style>
        </div>
      )}

      {/* Konfirmasi Hapus */}
      <ConfirmDialog
        isOpen={!!deleteConfirm}
        onClose={() => { setDeleteConfirm(null); setAlasanHapus('') }}
        onConfirm={handleHapus}
        tipe="hapus"
        judul="Hapus Invoice?"
        pesan="Invoice yang dihapus tidak bisa dikembalikan. Isi alasan penghapusan:"
        extra={
          <input
            value={alasanHapus}
            onChange={e => setAlasanHapus(e.target.value)}
            placeholder="Alasan penghapusan (opsional)"
            style={{ width: '100%', height: 36, borderRadius: 8, border: '1.5px solid #e2e8f0', padding: '0 12px', fontSize: 13, fontFamily: 'inherit', outline: 'none', marginTop: 8, boxSizing: 'border-box' }}
          />
        }
        detail={[
          { label: 'Nomor KW',   value: deleteConfirm?.nomorKW    || '-' },
          { label: 'Consignee',  value: deleteConfirm?.consignee   || '-' },
          { label: 'Jenis',      value: deleteConfirm?.jenisLayanan || '-' },
          { label: 'Grand Total',value: formatRupiah(deleteConfirm?.grandTotal || 0) },
        ]}
      />

    </div>
  )
}