// Invoice Aging
const { useState: useStateIA } = React;

function InvoiceAging({ collector, setPage, pushToast }) {
  const [bucket, setBucket] = useStateIA('all');
  let invoices = collector === 'all' ? INVOICES : INVOICES.filter(inv => CUSTOMER_BY_ID[inv.customerId].collectorId === collector);
  if (bucket !== 'all') invoices = invoices.filter(inv => agingBucket(inv) === bucket);
  const overdue = invoices.filter(inv => daysLate(inv) > 0).reduce((s,inv)=>s+invoiceBalance(inv),0);

  return (
    <>
      <PageHeader eyebrow="Aging Piutang" title="Invoice Aging Board" subtitle={`${invoices.length} invoice dalam filter, total overdue ${rupiah(overdue,{sym:true})}. Bucket 31+ hari otomatis masuk prioritas collector.`} actions={<><Btn icon="download" tone="primary">Ekspor XLS</Btn><Btn icon="bell" tone="outline" onClick={()=>setPage('followup')}>Reminder Massal</Btn></>} />
      <div className="row gap-2" style={{marginBottom:14, flexWrap:'wrap'}}>{[{id:'all',label:'Semua'}, {id:'current',label:'Current'}, {id:'d1',label:'1-7'}, {id:'d8',label:'8-30'}, {id:'d31',label:'31-60'}, {id:'d60',label:'60+'}].map(b => <button key={b.id} className={'btn ' + (bucket===b.id?'':'outline') + ' sm'} onClick={()=>setBucket(b.id)}>{b.label}</button>)}</div>
      <div className="aging-board" style={{marginBottom:16}}>{['current','d1','d8','d31','d60'].map(b => { const list=(collector==='all'?INVOICES:INVOICES.filter(inv=>CUSTOMER_BY_ID[inv.customerId].collectorId===collector)).filter(inv=>agingBucket(inv)===b); const total=list.reduce((s,inv)=>s+invoiceBalance(inv),0); return <div className={'aging-col ' + b} key={b}><div className="aging-col-head"><div className="aging-col-title">{bucketLabel(b)}</div><div className="aging-col-total">{rupiah(total,{compact:true})}</div><div className="text-sm">{list.length} invoice</div></div>{list.map(inv => <InvoiceMini key={inv.id} inv={inv} />)}</div>; })}</div>
      <Card><div style={{padding:'14px 16px', borderBottom:'1px solid hsl(var(--border))'}}><SectionHead title="Daftar Invoice" hint="Klik baris untuk follow-up" /></div><div style={{maxHeight:'52vh', overflowY:'auto'}}><table className="table"><thead style={{position:'sticky', top:0, background:'hsl(var(--card))', zIndex:1}}><tr><th>Invoice</th><th>Customer</th><th>Collector</th><th>Tgl Invoice</th><th>Jatuh Tempo</th><th>Umur</th><th style={{textAlign:'right'}}>Nilai</th><th style={{textAlign:'right'}}>Saldo</th><th>Status</th></tr></thead><tbody>{invoices.map(inv => { const c=CUSTOMER_BY_ID[inv.customerId]; const col=collectorById(c.collectorId); return <tr key={inv.id} onClick={()=>setPage('followup')} style={{cursor:'pointer'}}><td className="mono">{inv.id}</td><td><b>{c.name}</b><div className="text-sm muted">{c.area} · term {c.term}</div></td><td>{col.name}</td><td>{formatDateID(inv.issueDate)}</td><td>{formatDateID(inv.dueDate)}</td><td className="mono" style={{color:daysLate(inv)>30?'hsl(var(--destructive))':undefined}}>{daysLate(inv) > 0 ? `H+${daysLate(inv)}` : `H${daysLate(inv)}`}</td><td style={{textAlign:'right'}}>{rupiah(inv.amount,{sym:true})}</td><td style={{textAlign:'right', fontWeight:800}}>{rupiah(invoiceBalance(inv),{sym:true})}</td><td><StatusPill status={inv.status}/></td></tr>; })}</tbody></table></div></Card>
    </>
  );
}

function InvoiceMini({ inv }) {
  const c = CUSTOMER_BY_ID[inv.customerId];
  return <div className="invoice-card"><div className="row between"><span className="invoice-code">{inv.id}</span><StatusPill status={inv.status}/></div><div style={{fontWeight:750, marginTop:4}}>{c.name}</div><div className="row between text-sm muted" style={{marginTop:4}}><span>{daysLate(inv)>0?'H+'+daysLate(inv):'Current'}</span><span className="invoice-amount">{rupiah(invoiceBalance(inv),{compact:true})}</span></div>{inv.dispute && <div className="text-sm" style={{marginTop:5, color:'hsl(var(--destructive))'}}>Dispute: {inv.dispute}</div>}</div>;
}

window.InvoiceAging = InvoiceAging;
