/**
 * DaftarKonsolidasi.jsx — List dokumen konsolidasi ekspor
 * Flow: TERBUKA → PROSES (saat invoice terbit) → SELESAI (saat LUNAS)
 *
 * REVISI: Selaraskan aksi tombol dengan DaftarBTD/BDN
 *   - Tambah StatusTrackerModal
 *   - Tombol icon-based (Activity, ArrowRight, Trash2)
 *   - ConfirmDialog untuk hapus
 */
import { useState, useMemo } from 'react'
import { useNavigate } from 'react-router-dom'
import { useApp } from '../context/AppContext'
import { useDebounce } from '../hooks/useDebounce'
import ConfirmDialog from '../components/ConfirmDialog'
import StatusTrackerModal from '../components/StatusTrackerModal'
import PageHeader from '../components/PageHeader'
import { Search, Plus, Trash2, ArrowRight, Activity } from 'lucide-react'

const fmtTgl = (t) => {
  if (!t) return '—'
  try {
    const d = new Date(t)
    const b = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Agu','Sep','Okt','Nov','Des']
    return `${String(d.getDate()).padStart(2,'0')} ${b[d.getMonth()]} ${d.getFullYear()}`
  } catch { return t }
}

const STATUS_STYLE = {
  TERBUKA: { bg:'#f0fdf4', color:'#166534', dot:'#22c55e', label:'Terbuka' },
  PROSES:  { bg:'#fff7ed', color:'#c2410c', dot:'#f97316', label:'Proses' },
  SELESAI: { bg:'#f1f5f9', color:'#475569', dot:'#94a3b8', label:'Selesai' },
}

function StatusBadge({ status }) {
  const key = (status || 'TERBUKA').toUpperCase()
  const s = STATUS_STYLE[key] || STATUS_STYLE.TERBUKA
  return (
    <span style={{ display:'inline-flex', alignItems:'center', gap:5, fontSize:11, fontWeight:600, padding:'3px 9px', borderRadius:20, background:s.bg, color:s.color }}>
      <span style={{ width:6, height:6, borderRadius:'50%', background:s.dot, flexShrink:0 }} />
      {s.label}
    </span>
  )
}

function SegFilter({ label, options, value, onChange }) {
  return (
    <div style={{ display:'flex', border:'0.5px solid #e2e8f0', borderRadius:8, overflow:'hidden', flexShrink:0 }}>
      {[{ val:'', label }, ...options].map((o, i, arr) => (
        <button key={o.val} onClick={() => onChange(o.val === value ? '' : o.val)} style={{
          height:30, padding:'0 12px', fontSize:12, fontFamily:'inherit', cursor:'pointer',
          background: value === o.val ? '#1e293b' : 'white',
          color: value === o.val ? 'white' : '#64748b',
          border:'none', borderRight: i < arr.length-1 ? '0.5px solid #e2e8f0' : 'none',
          transition:'all .15s',
        }}>{o.label}</button>
      ))}
    </div>
  )
}

function SortIcon({ col, sortCol, sortDir }) {
  if (sortCol !== col) return <span style={{ opacity:.3, fontSize:9, marginLeft:3 }}>↕</span>
  return <span style={{ fontSize:9, marginLeft:3 }}>{sortDir === 'asc' ? '↑' : '↓'}</span>
}

export default function DaftarKonsolidasi() {
  const { konsolidasiList, hapusKonsolidasi, showToast, invoiceList } = useApp()
  const navigate = useNavigate()

  const [searchInput, setSearchInput] = useState('')
  const search = useDebounce(searchInput, 300)
  const [filterStatus, setFilterStatus] = useState('')
  const [filterJenis, setFilterJenis]   = useState('')
  const [sortCol, setSortCol]           = useState('createdAt')
  const [sortDir, setSortDir]           = useState('desc')
  const [deleteTarget, setDeleteTarget] = useState(null)
  const [trackerTarget, setTrackerTarget] = useState(null)

  const handleSort = (col) => {
    if (sortCol === col) setSortDir(d => d === 'asc' ? 'desc' : 'asc')
    else { setSortCol(col); setSortDir('asc') }
  }

  const filtered = useMemo(() => {
    let list = konsolidasiList.filter(d => {
      const q = search.toLowerCase()
      const matchSearch = !search ||
        d.bookingRefNo?.toLowerCase().includes(q) ||
        d.consignee?.toLowerCase().includes(q) ||
        d.containerNo?.toLowerCase().includes(q) ||
        d.vessel?.toLowerCase().includes(q)
      const matchStatus = !filterStatus || d.status?.toUpperCase() === filterStatus.toUpperCase()
      const matchJenis  = !filterJenis  || d.jenisKonsolidasi?.toUpperCase() === filterJenis.toUpperCase()
      return matchSearch && matchStatus && matchJenis
    })
    list = [...list].sort((a, b) => {
      let va = a[sortCol] ?? '', vb = b[sortCol] ?? ''
      if (sortCol === 'createdAt' || sortCol === 'tglStuffing') { va = new Date(va); vb = new Date(vb) }
      else { va = String(va).toLowerCase(); vb = String(vb).toLowerCase() }
      return sortDir === 'asc' ? (va > vb ? 1 : -1) : (va < vb ? 1 : -1)
    })
    return list
  }, [konsolidasiList, search, filterStatus, filterJenis, sortCol, sortDir])

  const stats = useMemo(() => ({
    total:   konsolidasiList.length,
    terbuka: konsolidasiList.filter(d => d.status?.toUpperCase() === 'TERBUKA').length,
    proses:  konsolidasiList.filter(d => d.status?.toUpperCase() === 'PROSES').length,
    selesai: konsolidasiList.filter(d => d.status?.toUpperCase() === 'SELESAI').length,
    lcl:     konsolidasiList.filter(d => d.jenisKonsolidasi === 'LCL').length,
    fcl:     konsolidasiList.filter(d => d.jenisKonsolidasi === 'FCL').length,
  }), [konsolidasiList])

  const handleHapus = async () => {
    try {
      await hapusKonsolidasi(deleteTarget.id)
      showToast(`Dokumen konsolidasi ${deleteTarget.bookingRefNo} berhasil dihapus`, 'sukses')
    } catch {
      // Error sudah ditampilkan oleh hapusKonsolidasi via showToast di AppContext
    } finally {
      setDeleteTarget(null)
    }
  }

  const handleTransaksi = (d) => {
    navigate('/konsolidasi/transaksi', { state: { docId: d.id } })
  }

  const handleResetFilter = () => {
    setSearchInput('')
    setFilterStatus('')
    setFilterJenis('')
  }

  const td = { padding:'11px 14px', fontSize:12.5, color:'#0f172a', borderBottom:'0.5px solid #f1f5f9', verticalAlign:'middle', whiteSpace:'nowrap' }
  const th = { padding:'9px 14px', fontSize:10, fontWeight:600, textTransform:'uppercase', letterSpacing:'.07em', color:'#94a3b8', background:'#f8fafc', borderBottom:'0.5px solid #e2e8f0', whiteSpace:'nowrap', cursor:'pointer', userSelect:'none' }
  const tdFz = { ...td, position:'sticky', left:0, zIndex:1, background:'white', borderRight:'0.5px solid #e2e8f0' }
  const thFz = { ...th, position:'sticky', left:0, zIndex:2, background:'#f8fafc', borderRight:'0.5px solid #e2e8f0' }

  return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', minHeight:0 }}>
      <div style={{ padding:'20px 32px 0', display:'flex', alignItems:'flex-start', justifyContent:'space-between' }}>
        <div>
          <h1 style={{ fontSize:20, fontWeight:700, color:'#0f172a', margin:0 }}>Daftar Konsolidasi Ekspor</h1>
          <p style={{ fontSize:12, color:'#94a3b8', marginTop:3 }}>Dokumen konsolidasi OB LCL / ALL IN FCL</p>
        </div>
        <button onClick={() => navigate('/konsolidasi/input')} style={{ height:36, padding:'0 16px', borderRadius:8, border:'none', background:'#f59e0b', color:'white', fontSize:13, fontWeight:600, fontFamily:'inherit', cursor:'pointer', display:'flex', alignItems:'center', gap:7 }}>
          <Plus size={14} /> Input Konsolidasi
        </button>
      </div>

      {/* Stats bar */}
      <div style={{ display:'flex', gap:0, margin:'16px 32px 0', background:'white', border:'0.5px solid #e2e8f0', borderRadius:12, overflow:'hidden' }}>
        {[
          { label:'Total Dokumen', val:stats.total,   color:'#94a3b8' },
          { label:'Terbuka',       val:stats.terbuka, color:'#22c55e' },
          { label:'Proses',        val:stats.proses,  color:'#f97316' },
          { label:'Selesai',       val:stats.selesai, color:'#94a3b8' },
          { label:'OB LCL',       val:stats.lcl,     color:'#7c3aed' },
          { label:'ALL IN FCL',   val:stats.fcl,     color:'#3b82f6' },
        ].map((s, i, arr) => (
          <div key={s.label} style={{ flex:1, padding:'10px 16px', borderRight: i < arr.length-1 ? '0.5px solid #f1f5f9' : 'none', display:'flex', alignItems:'center', gap:10 }}>
            <div style={{ width:3, height:26, borderRadius:2, background:s.color, flexShrink:0 }} />
            <div>
              <div style={{ fontSize:18, fontWeight:700, color: s.val > 0 ? '#0f172a' : '#cbd5e1', lineHeight:1 }}>{s.val}</div>
              <div style={{ fontSize:10.5, color:'#94a3b8', marginTop:2 }}>{s.label}</div>
            </div>
          </div>
        ))}
      </div>

      {/* Filter bar */}
      <div style={{ display:'flex', gap:8, margin:'12px 32px 0', alignItems:'center', flexWrap:'wrap' }}>
        <div style={{ position:'relative', flex:1, minWidth:220 }}>
          <Search size={13} style={{ position:'absolute', left:10, top:'50%', transform:'translateY(-50%)', color:'#94a3b8', pointerEvents:'none' }} />
          <input value={searchInput} onChange={e => setSearchInput(e.target.value)}
            placeholder="Cari Booking Ref, EMKL, Container..."
            style={{ width:'100%', height:34, borderRadius:8, border:'0.5px solid #e2e8f0', paddingLeft:32, paddingRight:10, fontSize:12.5, fontFamily:'inherit', outline:'none', background:'white', boxSizing:'border-box', color:'#0f172a' }}
          />
        </div>
        <SegFilter
          label="Semua Status"
          options={[{val:'TERBUKA',label:'Terbuka'},{val:'PROSES',label:'Proses'},{val:'SELESAI',label:'Selesai'}]}
          value={filterStatus}
          onChange={setFilterStatus}
        />
        <SegFilter
          label="Semua Jenis"
          options={[{val:'LCL',label:'OB LCL'},{val:'FCL',label:'ALL IN FCL'}]}
          value={filterJenis}
          onChange={setFilterJenis}
        />
        {(search || filterStatus || filterJenis) && (
          <button onClick={handleResetFilter}
            style={{ height:30, padding:'0 12px', fontSize:12, color:'#ef4444', background:'#fff5f5', border:'0.5px solid #fecaca', borderRadius:8, cursor:'pointer', fontFamily:'inherit', fontWeight:600 }}>
            Hapus Filter ✕
          </button>
        )}
      </div>

      {/* Table */}
      <div style={{ margin:'12px 32px 32px', background:'white', border:'0.5px solid #e2e8f0', borderRadius:12, overflow:'hidden', display:'flex', flexDirection:'column' }}>
        <div style={{ overflowX:'auto' }}>
          <table style={{ width:'100%', borderCollapse:'collapse', minWidth:960 }}>
            <thead>
              <tr>
                <th style={thFz} onClick={() => handleSort('bookingRefNo')}>Booking Ref <SortIcon col="bookingRefNo" sortCol={sortCol} sortDir={sortDir} /></th>
                <th style={{ ...th, minWidth:170 }} onClick={() => handleSort('consignee')}>EMKL <SortIcon col="consignee" sortCol={sortCol} sortDir={sortDir} /></th>
                <th style={{ ...th, minWidth:130 }}>Container</th>
                <th style={{ ...th, minWidth:160 }}>Vessel / Voyage</th>
                <th style={{ ...th, minWidth:110 }} onClick={() => handleSort('tglStuffing')}>Tgl Stuffing <SortIcon col="tglStuffing" sortCol={sortCol} sortDir={sortDir} /></th>
                <th style={{ ...th, minWidth:90 }}>Jenis</th>
                <th style={{ ...th, minWidth:95 }}>Status</th>
                <th style={{ ...th, minWidth:120 }}>Invoice</th>
                <th style={{ ...th, minWidth:105, cursor:'default' }}>Aksi</th>
              </tr>
            </thead>
            <tbody>
              {filtered.length === 0 ? (
                <tr>
                  <td colSpan={9} style={{ padding:'48px 20px', textAlign:'center' }}>
                    <div style={{ fontSize:13, color:'#94a3b8', fontWeight:500 }}>
                      {konsolidasiList.length === 0 ? 'Belum ada dokumen konsolidasi.' : 'Tidak ada yang sesuai filter.'}
                    </div>
                    {konsolidasiList.length === 0 && (
                      <button onClick={() => navigate('/konsolidasi/input')} style={{ marginTop:10, fontSize:12.5, color:'#f59e0b', background:'none', border:'none', cursor:'pointer', fontFamily:'inherit', fontWeight:600 }}>
                        + Input Konsolidasi pertama
                      </button>
                    )}
                  </td>
                </tr>
              ) : filtered.map(d => {
                const invs = invoiceList.filter(inv => inv.konsolidasiDokumenId === d.id)
                const isSelesai = d.status?.toUpperCase() === 'SELESAI'
                const isTerbuka = d.status?.toUpperCase() === 'TERBUKA'
                const hasActiveInvoice = invs.length > 0

                return (
                  <tr key={d.id}
                    onMouseEnter={e => Array.from(e.currentTarget.cells).forEach(c => c.style.background = '#fefce8')}
                    onMouseLeave={e => { Array.from(e.currentTarget.cells).forEach(c => c.style.background = ''); e.currentTarget.cells[0].style.background = 'white' }}
                  >
                    <td style={tdFz}>
                      <div style={{ fontFamily:'monospace', fontSize:12, fontWeight:700, color:'#d97706', maxWidth:160, overflow:'hidden', textOverflow:'ellipsis' }}>{d.bookingRefNo || '—'}</div>
                    </td>
                    <td style={{ ...td, maxWidth:200 }}>
                      <div style={{ fontWeight:600, fontSize:13, overflow:'hidden', textOverflow:'ellipsis' }}>{d.consignee || '—'}</div>
                    </td>
                    <td style={{ ...td, fontFamily:'monospace', fontSize:12, color:'#0f172a' }}>
                      {d.containerNo || '—'}
                      {d.ukuran && <span style={{ fontSize:11, color:'#64748b', marginLeft:4 }}>({d.ukuran})</span>}
                    </td>
                    <td style={{ ...td, color:'#64748b', fontSize:12, maxWidth:160, overflow:'hidden', textOverflow:'ellipsis' }}>
                      {d.vessel || '—'}
                      {d.voyage && <span style={{ fontSize:11, color:'#94a3b8' }}> / {d.voyage}</span>}
                    </td>
                    <td style={{ ...td, color:'#64748b', fontSize:12 }}>{fmtTgl(d.tglStuffing)}</td>
                    <td style={td}>
                      <span style={{
                        fontSize:10.5, fontWeight:700, padding:'2px 8px', borderRadius:5,
                        background: d.jenisKonsolidasi === 'LCL' ? '#f5f3ff' : '#eff6ff',
                        color: d.jenisKonsolidasi === 'LCL' ? '#6d28d9' : '#1d4ed8',
                      }}>
                        {d.jenisKonsolidasi === 'LCL' ? 'OB LCL' : 'ALL IN FCL'}
                      </span>
                    </td>
                    <td style={td}><StatusBadge status={d.status} /></td>
                    <td style={{ ...td, fontSize:12, color:'#475569' }}>
                      {invs.length > 0 ? invs.map(inv => (
                        <div key={inv.id} style={{ fontSize:11.5, fontWeight:600, color:'#0ea5e9', fontFamily:'monospace' }}>
                          {inv.nomorKW}
                        </div>
                      )) : <span style={{ color:'#cbd5e1' }}>—</span>}
                    </td>
                    <td style={td}>
                      <div style={{ display:'flex', gap:5, alignItems:'center' }}>
                        <button onClick={() => setTrackerTarget(d)} title="Status Tracker" style={{ width:30, height:30, borderRadius:7, border:'0.5px solid #e9d5ff', background:'#faf5ff', color:'#7c3aed', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                          <Activity size={13} />
                        </button>
                        <button onClick={() => isTerbuka && handleTransaksi(d)} title={isSelesai ? 'Sudah selesai' : isTerbuka ? 'Lanjut Transaksi' : 'Sudah ada invoice'} style={{ width:30, height:30, borderRadius:7, border:`0.5px solid ${isTerbuka?'#fde68a':'#e2e8f0'}`, background: isTerbuka?'#fffbeb':'#f8fafc', color: isTerbuka?'#d97706':'#cbd5e1', cursor: isTerbuka?'pointer':'default', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                          <ArrowRight size={13} />
                        </button>
                        <button onClick={() => setDeleteTarget(d)} title="Hapus" style={{ width:30, height:30, borderRadius:7, border:'0.5px solid #fecaca', background:'#fff5f5', color:'#dc2626', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                          <Trash2 size={13} />
                        </button>
                      </div>
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>
        </div>

        {filtered.length > 0 && (
          <div style={{ padding:'9px 16px', borderTop:'0.5px solid #f1f5f9', background:'#f8fafc', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
            <span style={{ fontSize:11.5, color:'#94a3b8' }}>
              Menampilkan <strong style={{ color:'#64748b' }}>{filtered.length}</strong> dari <strong style={{ color:'#64748b' }}>{konsolidasiList.length}</strong> dokumen
              {(search || filterStatus || filterJenis) && ' · filter aktif'}
            </span>
            <span style={{ fontSize:11, color:'#cbd5e1' }}>† scroll untuk lihat lebih →</span>
          </div>
        )}
      </div>

      <StatusTrackerModal dokumen={trackerTarget} tipe="konsolidasi" invoiceList={invoiceList} onClose={() => setTrackerTarget(null)} />
      <ConfirmDialog
        isOpen={!!deleteTarget} onClose={() => setDeleteTarget(null)} onConfirm={handleHapus}
        tipe="hapus" judul="Hapus Dokumen Konsolidasi?"
        pesan="Dokumen ini akan dihapus permanen. Pastikan tidak ada invoice aktif yang terkait."
        detail={[{ label:'Booking Ref', value:deleteTarget?.bookingRefNo }, { label:'EMKL', value:deleteTarget?.consignee }]}
      />
    </div>
  )
}
