// Riwayat servis — timeline view of service history with filters
const { useState: useStateRw, useMemo: useMemoRw } = React;

function RiwayatPage({ role }) {
  const [period, setPeriod] = useStateRw('all');
  const [cabang, setCabang] = useStateRw('all');
  const [q, setQ] = useStateRw('');
  const [selected, setSelected] = useStateRw(null);

  const filtered = useMemoRw(() => {
    return SERVIS_HISTORY.filter(s => {
      if (cabang !== 'all' && s.cabang !== cabang) return false;
      if (period === '30d' && daysToExpiry(s.tgl) < -30) return false;
      if (period === '7d'  && daysToExpiry(s.tgl) < -7)  return false;
      if (q) {
        const vh = KENDARAAN_BY_ID[s.vhId];
        const ow = OWNER_BY_ID[vh?.ownerId];
        const hay = `${vh?.plat} ${vh?.merk} ${vh?.model} ${ow?.name}`.toLowerCase();
        if (!hay.includes(q.toLowerCase())) return false;
      }
      return true;
    }).sort((a, b) => b.tgl.localeCompare(a.tgl));
  }, [period, cabang, q]);

  // Group by month
  const byMonth = {};
  filtered.forEach(s => {
    const m = s.tgl.slice(0, 7);
    (byMonth[m] ||= []).push(s);
  });
  const months = Object.keys(byMonth).sort().reverse();

  const totalRevenue = filtered.reduce((s, h) => s + h.total, 0);

  return (
    <div>
      <PageHeader
        eyebrow="Catatan"
        title="Riwayat Servis"
        subtitle={`${filtered.length} servis dari ${SERVIS_HISTORY.length} record (filter aktif)`}
        actions={<><Btn icon="download" tone="outline">Export CSV</Btn></>}
      />

      <div className="grid mb-6" style={{gridTemplateColumns:'repeat(4, 1fr)', gap:12}}>
        <Kpi label="Total Servis" value={filtered.length} hint="period filter" icon="history" tone="info" />
        <Kpi label="Revenue" value={rupiah(totalRevenue, {compact:true})} hint="dari item jasa" icon="dollar" tone="good" />
        <Kpi label="Avg per WO" value={rupiah(Math.round(totalRevenue / (filtered.length || 1)), {compact:true})} hint="rata-rata transaksi" icon="receipt" tone="accent" />
        <Kpi label="Foto Tersimpan" value={filtered.reduce((s, h) => s + (h.foto || 0), 0)} hint="dokumentasi" icon="camera" tone="info" />
      </div>

      <Card style={{padding:14, marginBottom:14}}>
        <div className="row gap-2" style={{flexWrap:'wrap', alignItems:'center'}}>
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Cari plat, owner, atau merk…" style={{flex:1, minWidth:200, padding:'8px 12px', border:'1px solid hsl(var(--border))', borderRadius:8, fontSize:13, background:'hsl(var(--card))'}} />
          <select value={period} onChange={e => setPeriod(e.target.value)} style={{padding:'8px 10px', border:'1px solid hsl(var(--border))', borderRadius:8, fontSize:13, background:'hsl(var(--card))'}}>
            <option value="all">Semua periode</option>
            <option value="30d">30 hari terakhir</option>
            <option value="7d">7 hari terakhir</option>
          </select>
          <select value={cabang} onChange={e => setCabang(e.target.value)} style={{padding:'8px 10px', border:'1px solid hsl(var(--border))', borderRadius:8, fontSize:13, background:'hsl(var(--card))'}}>
            <option value="all">Semua cabang</option>
            {CABANG.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
        </div>
      </Card>

      <div className="svc-timeline">
        {months.map(m => (
          <div key={m} style={{marginBottom:18}}>
            <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:10}}>
              <h3 style={{margin:0, fontFamily:'Fraunces, Georgia, serif', fontSize:16, fontWeight:650}}>{formatDateID(m + '-01').replace(/\d+ /, '')}</h3>
              <Pill tone="muted">{byMonth[m].length} servis</Pill>
            </div>
            <div className="flex-col gap-2">
              {byMonth[m].map(h => {
                const vh = KENDARAAN_BY_ID[h.vhId];
                const ow = OWNER_BY_ID[vh?.ownerId];
                const mk = MEKANIK_BY_ID[h.mekanikId];
                return (
                  <Card key={h.id} style={{padding:14, cursor:'pointer'}} onClick={() => setSelected(h)}>
                    <div className="row" style={{justifyContent:'space-between', alignItems:'flex-start', gap:14}}>
                      <div style={{flex:1}}>
                        <div className="row gap-2" style={{alignItems:'center', marginBottom:6}}>
                          <div style={{fontFamily:'Fraunces, Georgia, serif', fontSize:14, fontWeight:650}}>{vh?.merk} {vh?.model}</div>
                          <span className="mono" style={{fontSize:11, color:'hsl(var(--muted-foreground))'}}>{vh?.plat}</span>
                          <Pill tone="muted">{cabangName(h.cabang)}</Pill>
                        </div>
                        <div style={{fontSize:12, color:'hsl(var(--muted-foreground))', marginBottom:6}}>
                          {formatDateID(h.tgl)} · {ow?.name} · km {h.km.toLocaleString('id-ID')}
                        </div>
                        <div className="row gap-1" style={{flexWrap:'wrap'}}>
                          {h.items.map(id => <span key={id} className="svc-item-chip">{ITEM_SERVIS_BY_ID[id]?.label}</span>)}
                        </div>
                        {h.catatan && h.catatan !== '-' && (
                          <div style={{fontSize:12, color:'hsl(var(--muted-foreground))', marginTop:6, fontStyle:'italic'}}>"{h.catatan}"</div>
                        )}
                      </div>
                      <div style={{textAlign:'right', minWidth:120}}>
                        <div className="mono" style={{fontSize:15, fontWeight:700}}>{rupiah(h.total, {compact:true})}</div>
                        <div className="row gap-1" style={{justifyContent:'flex-end', alignItems:'center', marginTop:4, fontSize:11, color:'hsl(var(--muted-foreground))'}}>
                          <Avatar initials={mk?.initials} className="sm" tone="accent" />
                          <span>{mk?.name?.split(' ')[0]}</span>
                        </div>
                        <div style={{fontSize:11, color:'hsl(var(--muted-foreground))', marginTop:4}}>
                          <Icon name="camera" size={11} /> {h.foto} foto
                        </div>
                      </div>
                    </div>
                  </Card>
                );
              })}
            </div>
          </div>
        ))}
        {months.length === 0 && (
          <Card style={{padding:32, textAlign:'center', color:'hsl(var(--muted-foreground))'}}>Tidak ada riwayat sesuai filter.</Card>
        )}
      </div>

      {selected && (
        <div className="drawer-overlay" onClick={() => setSelected(null)}>
          <div className="drawer" onClick={e => e.stopPropagation()}>
            <div className="drawer-head">
              <div>
                <Pill tone="good" dot>Servis Selesai</Pill>
                <h2 style={{margin:'6px 0 2px', fontFamily:'Fraunces, Georgia, serif', fontSize:20, fontWeight:650}}>{KENDARAAN_BY_ID[selected.vhId]?.merk} {KENDARAAN_BY_ID[selected.vhId]?.model}</h2>
                <div style={{fontSize:13, color:'hsl(var(--muted-foreground))'}}>{formatDateID(selected.tgl)} · {selected.id}</div>
              </div>
              <Btn icon="x" tone="ghost" onClick={() => setSelected(null)}>Tutup</Btn>
            </div>
            <div className="drawer-body">
              <Card style={{padding:14, marginBottom:12}}>
                <div className="grid" style={{gridTemplateColumns:'repeat(2, 1fr)', gap:10, fontSize:13}}>
                  <div><div style={{fontSize:11, color:'hsl(var(--muted-foreground))', textTransform:'uppercase', letterSpacing:0.4, fontWeight:600}}>Plat</div><div className="mono">{KENDARAAN_BY_ID[selected.vhId]?.plat}</div></div>
                  <div><div style={{fontSize:11, color:'hsl(var(--muted-foreground))', textTransform:'uppercase', letterSpacing:0.4, fontWeight:600}}>KM saat servis</div><div className="mono">{selected.km.toLocaleString('id-ID')}</div></div>
                  <div><div style={{fontSize:11, color:'hsl(var(--muted-foreground))', textTransform:'uppercase', letterSpacing:0.4, fontWeight:600}}>Owner</div><div>{OWNER_BY_ID[KENDARAAN_BY_ID[selected.vhId]?.ownerId]?.name}</div></div>
                  <div><div style={{fontSize:11, color:'hsl(var(--muted-foreground))', textTransform:'uppercase', letterSpacing:0.4, fontWeight:600}}>Mekanik</div><div>{MEKANIK_BY_ID[selected.mekanikId]?.name}</div></div>
                </div>
              </Card>
              <SectionHead title="Item Servis" />
              <Card style={{padding:0, marginBottom:12}}>
                {selected.items.map((id, idx) => {
                  const it = ITEM_SERVIS_BY_ID[id];
                  return (
                    <div key={id} style={{display:'flex', justifyContent:'space-between', alignItems:'center', padding:'10px 14px', borderTop: idx === 0 ? 'none' : '1px solid hsl(var(--border))'}}>
                      <span style={{fontSize:13}}>{it?.label}</span>
                      <span className="mono" style={{fontSize:13, fontWeight:600}}>{rupiah(it?.hargaJasa, {compact:true})}</span>
                    </div>
                  );
                })}
                <div style={{padding:'10px 14px', borderTop:'1px solid hsl(var(--border))', background:'hsl(var(--muted) / 0.3)', display:'flex', justifyContent:'space-between'}}>
                  <span style={{fontSize:13, fontWeight:650}}>Total</span>
                  <span className="mono" style={{fontSize:15, fontWeight:700}}>{rupiah(selected.total)}</span>
                </div>
              </Card>
              {selected.catatan && selected.catatan !== '-' && (
                <Card style={{padding:14}}>
                  <div style={{fontSize:11, color:'hsl(var(--muted-foreground))', textTransform:'uppercase', letterSpacing:0.4, fontWeight:600, marginBottom:6}}>Catatan Mekanik</div>
                  <div style={{fontSize:13, lineHeight:1.5}}>{selected.catatan}</div>
                </Card>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.RiwayatPage = RiwayatPage;
