// Transaksi — riwayat struk, filter, refund
const { useState: useStateT, useMemo: useMemoT } = React;

function Transaksi({ cabang, role }) {
  const [filter, setFilter] = useStateT({ method: 'all', kasir: 'all' });
  const [selected, setSelected] = useStateT(null);
  const canRefund = ROLES[role].can.refund;

  const list = TRANSAKSI.filter(t => {
    if (cabang !== 'all' && t.cabang !== cabang) return false;
    if (filter.method !== 'all' && t.method !== filter.method) return false;
    if (filter.kasir !== 'all' && t.kasir !== filter.kasir) return false;
    return true;
  }).slice().reverse();

  const total = list.reduce((s, t) => s + t.total, 0);
  const cashTotal = list.filter(t => t.method === 'cash').reduce((s, t) => s + t.total, 0);
  const cashlessTotal = total - cashTotal;
  const kasirNames = [...new Set(TRANSAKSI.map(t => t.kasir))];

  return (
    <div className="stack-6">
      <div className="grid-4">
        <Kpi label="Transaksi"     value={list.length.toString()} hint={`Filter aktif: ${filter.method === 'all' ? 'semua metode' : methodLabel(filter.method)}`} icon="receipt" />
        <Kpi label="Total Omzet"   value={rupiah(total, { sym: true })} icon="trending" />
        <Kpi label="Tunai"         value={rupiah(cashTotal, { sym: true, compact: true })} hint={`${list.length ? Math.round(cashTotal / total * 100) : 0}% dari total`} icon="cashbox" />
        <Kpi label="Cashless"      value={rupiah(cashlessTotal, { sym: true, compact: true })} hint="QRIS + Transfer + Debit" icon="qris" />
      </div>

      <Card>
        <div className="card-pad">
          <div className="row between mb-4">
            <div className="row gap-2">
              <select className="input" value={filter.method} onChange={e => setFilter(f => ({...f, method: e.target.value}))}>
                <option value="all">Semua metode</option>
                <option value="cash">Tunai</option>
                <option value="qris">QRIS</option>
                <option value="transfer">Transfer</option>
                <option value="kartu">Debit/Kredit</option>
              </select>
              <select className="input" value={filter.kasir} onChange={e => setFilter(f => ({...f, kasir: e.target.value}))}>
                <option value="all">Semua kasir</option>
                {kasirNames.map(n => <option key={n} value={n}>{n}</option>)}
              </select>
            </div>
            <div className="row gap-2">
              <Btn icon="download" size="sm">Export</Btn>
              <Btn icon="print" size="sm">Cetak Rekap Z</Btn>
            </div>
          </div>

          <table className="table">
            <thead>
              <tr>
                <th>ID Transaksi</th>
                <th>Waktu</th>
                <th>Kasir</th>
                <th>Cabang</th>
                <th>Metode</th>
                <th style={{textAlign:'right'}}>Item</th>
                <th style={{textAlign:'right'}}>Total</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {list.map(t => (
                <tr key={t.id} onClick={() => setSelected(t)} style={{cursor:'pointer'}}>
                  <td><span className="mono">{t.id}</span></td>
                  <td>{t.time}</td>
                  <td>{t.kasir}</td>
                  <td>{CABANG_LIST.find(c => c.id === t.cabang)?.name}</td>
                  <td><Pill tone={t.method === 'cash' ? 'neutral' : 'accent'}>{methodLabel(t.method)}</Pill></td>
                  <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums'}}>{t.items}</td>
                  <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums', fontWeight:500}}>{rupiah(t.total)}</td>
                  <td style={{textAlign:'right'}}>
                    <button className="btn ghost sm"><Icon name="chevronRight" size={14} /></button>
                  </td>
                </tr>
              ))}
              {list.length === 0 && (
                <tr><td colSpan="8"><div className="empty">Tidak ada transaksi yang cocok.</div></td></tr>
              )}
            </tbody>
            <tfoot>
              <tr>
                <td colSpan="6" style={{textAlign:'right', fontWeight:600}}>Total</td>
                <td style={{textAlign:'right', fontWeight:600, fontVariantNumeric:'tabular-nums'}}>{rupiah(total, { sym: true })}</td>
                <td></td>
              </tr>
            </tfoot>
          </table>
        </div>
      </Card>

      <Card>
        <div className="card-pad">
          <SectionHead
            title="Refund Terkini"
            hint="Pengembalian barang dalam 7 hari terakhir"
            action={canRefund ? <Btn tone="outline" icon="rotate" size="sm">Buat Refund</Btn> : null}
          />
          <table className="table compact">
            <thead><tr><th>ID Refund</th><th>Tgl</th><th>Trx Asal</th><th>Kasir</th><th>Alasan</th><th style={{textAlign:'right'}}>Nilai</th><th>Status</th></tr></thead>
            <tbody>
              {REFUNDS.map(r => (
                <tr key={r.id}>
                  <td><span className="mono">{r.id}</span></td>
                  <td>{formatDateID(r.date)}</td>
                  <td><span className="mono">{r.trx}</span></td>
                  <td>{r.kasir}</td>
                  <td>{r.reason}</td>
                  <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums'}}>{rupiah(r.amount)}</td>
                  <td><Pill tone="success">{r.status}</Pill></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>

      {selected && <TrxDrawer t={selected} onClose={() => setSelected(null)} canRefund={canRefund} />}
    </div>
  );
}

function TrxDrawer({ t, onClose, canRefund }) {
  // Synthesise line items based on item count
  const items = useMemoT(() => {
    const pool = PRODUCTS.slice(0, 18);
    const seed = parseInt(t.id.slice(-4), 10);
    const lines = [];
    let target = t.total;
    for (let i = 0; i < t.items; i++) {
      const p = pool[(seed + i * 7) % pool.length];
      const qty = i === t.items - 1 ? Math.max(1, Math.round(target / p.price)) : Math.max(1, Math.floor((target / (t.items - i)) / p.price));
      const line = { p, qty, subtotal: p.price * qty };
      lines.push(line);
      target -= line.subtotal;
    }
    return lines;
  }, [t]);
  const subtotal = items.reduce((s, l) => s + l.subtotal, 0);

  return (
    <div className="drawer-backdrop" onMouseDown={onClose}>
      <div className="drawer" onMouseDown={e => e.stopPropagation()}>
        <div className="drawer-header">
          <div>
            <div style={{fontSize:11, color:'hsl(var(--muted-foreground))', fontFamily:'JetBrains Mono, monospace'}}>{t.id}</div>
            <h3 style={{margin:'4px 0 0', fontSize:18, fontWeight:600}}>{rupiah(t.total, { sym: true })}</h3>
            <div style={{fontSize:12, color:'hsl(var(--muted-foreground))', marginTop:2}}>
              {t.kasir} · {CABANG_LIST.find(c => c.id === t.cabang)?.name} · {t.time}
            </div>
          </div>
          <button className="btn ghost sm" onClick={onClose}><Icon name="x" size={14} /></button>
        </div>
        <div className="drawer-body">
          <SectionHead title="Detail Item" hint={`${t.items} item · ${methodLabel(t.method)}`} />
          <table className="table compact mb-6">
            <thead><tr><th>SKU</th><th>Produk</th><th style={{textAlign:'right'}}>Qty</th><th style={{textAlign:'right'}}>Subtotal</th></tr></thead>
            <tbody>
              {items.map((l, i) => (
                <tr key={i}>
                  <td><span className="mono">{l.p.sku}</span></td>
                  <td>{l.p.name}</td>
                  <td style={{textAlign:'right'}}>{l.qty}</td>
                  <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums'}}>{rupiah(l.subtotal)}</td>
                </tr>
              ))}
            </tbody>
            <tfoot>
              <tr><td colSpan="3" style={{textAlign:'right', fontWeight:600}}>Total</td><td style={{textAlign:'right', fontWeight:600, fontVariantNumeric:'tabular-nums'}}>{rupiah(subtotal, { sym: true })}</td></tr>
            </tfoot>
          </table>
          <div className="row gap-2">
            <Btn icon="print">Cetak Ulang Struk</Btn>
            {canRefund && <Btn tone="destructive" icon="rotate">Refund</Btn>}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Transaksi });
