// Apotek & Resep — pharmacy & prescription dispensing
const { useState: useStateAP } = React;

function Apotek({ role, pushToast }) {
  const [tab, setTab] = useStateAP('resep');

  const pendingResep = RESEP.filter(r => r.status === 'pending');
  const dispensedResep = RESEP.filter(r => r.status === 'dispensed');
  const lowStock = OBAT.filter(o => o.stock < o.par);
  const obatValue = OBAT.reduce((s, o) => s + o.stock * o.harga, 0);

  return (
    <>
      <PageHeader
        eyebrow="Apotek Klinik"
        title="Resep & Stok Obat"
        subtitle={`${pendingResep.length} resep menunggu dispensing, ${dispensedResep.length} sudah diserahkan hari ini. ${lowStock.length} item obat di bawah par stock — perlu pemesanan ulang.`}
        actions={<>
          <Btn icon="plus" tone="primary" onClick={()=>pushToast({msg:'Form resep manual'})}>Resep Manual</Btn>
          <Btn icon="upload" tone="outline" onClick={()=>pushToast({msg:'Penerimaan stok obat'})}>Terima Stok</Btn>
          <Btn icon="download" tone="outline">Laporan Apotek</Btn>
        </>}
      />

      <div className="grid g-4" style={{marginBottom:18}}>
        <Kpi label="Resep Pending" value={pendingResep.length} sub="Menunggu dispensing" icon="package" tone="amber"/>
        <Kpi label="Resep Diserahkan" value={dispensedResep.length} sub="Hari ini" icon="check" tone="green"/>
        <Kpi label="Stok Item" value={OBAT.length} sub={`${lowStock.length} perlu restock`} icon="package" tone={lowStock.length > 3 ? 'rose' : 'accent'}/>
        <Kpi label="Nilai Persediaan" value={rupiah(obatValue, {sym:true, compact:true})} sub="Harga beli × stok aktif" icon="dollar" tone="violet"/>
      </div>

      <div className="row gap-2" style={{marginBottom:14}}>
        {[
          {id:'resep', label:'Antrian Resep', count: pendingResep.length},
          {id:'dispensed', label:'Diserahkan Hari Ini', count: dispensedResep.length},
          {id:'stok', label:'Stok Obat', count: OBAT.length},
        ].map(t => (
          <button key={t.id} onClick={()=>setTab(t.id)} className={'btn ' + (tab === t.id ? '' : 'outline') + ' sm'}>
            {t.label} <span style={{marginLeft:6, opacity:0.7, fontVariantNumeric:'tabular-nums'}}>{t.count}</span>
          </button>
        ))}
      </div>

      {tab === 'resep' && (
        <div className="grid" style={{gridTemplateColumns:'1fr 1fr', gap:16}}>
          {pendingResep.length === 0 && (
            <Card><div style={{padding:'40px 20px', textAlign:'center', color:'hsl(var(--muted-foreground))'}}>Tidak ada resep menunggu.</div></Card>
          )}
          {pendingResep.map(r => <ResepCard key={r.id} r={r} pushToast={pushToast}/>)}
        </div>
      )}

      {tab === 'dispensed' && (
        <div className="grid" style={{gridTemplateColumns:'1fr 1fr', gap:16}}>
          {dispensedResep.map(r => <ResepCard key={r.id} r={r} pushToast={pushToast}/>)}
        </div>
      )}

      {tab === 'stok' && (
        <Card>
          <div style={{padding:'12px 16px', borderBottom:'1px solid hsl(var(--border))'}}>
            <SectionHead title="Stok Obat & Alkes" hint={`${OBAT.length} SKU aktif · ${lowStock.length} di bawah par`}/>
          </div>
          <div style={{maxHeight:'62vh', overflowY:'auto'}}>
            <table className="table">
              <thead style={{position:'sticky', top:0, background:'hsl(var(--card))', zIndex:1}}>
                <tr>
                  <th>SKU</th>
                  <th>Nama Obat</th>
                  <th>Kategori</th>
                  <th>Supplier</th>
                  <th style={{textAlign:'right'}}>Harga</th>
                  <th style={{textAlign:'right'}}>Stok / Par</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                {OBAT.map(o => {
                  const ratio = o.stock / o.par;
                  const cls = ratio < 0.5 ? 'stock-row-critical' : ratio < 1 ? 'stock-row-low' : '';
                  return (
                    <tr key={o.sku} className={cls}>
                      <td><span className="mono" style={{fontSize:11.5}}>{o.sku}</span></td>
                      <td><div style={{fontWeight:500}}>{o.nama}</div></td>
                      <td style={{fontSize:12}}>{o.kategori}</td>
                      <td style={{fontSize:12}}>{o.supplier}</td>
                      <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums'}}>{rupiah(o.harga, {sym:true})}</td>
                      <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums', fontWeight:500}}>{o.stock} <span style={{color:'hsl(var(--muted-foreground))', fontWeight:400}}>/ {o.par}</span> <span style={{fontSize:10.5, color:'hsl(var(--muted-foreground))', fontWeight:400}}>{o.satuan}</span></td>
                      <td>
                        {ratio < 0.5 ? <PastelPill color="rose">Kritis</PastelPill>
                          : ratio < 1 ? <PastelPill color="amber">Rendah</PastelPill>
                          : <PastelPill color="green">Aman</PastelPill>}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </Card>
      )}
    </>
  );
}

function ResepCard({ r, pushToast }) {
  const p = PASIEN_BY_ID[r.pasienId];
  const d = DOKTER.find(x => x.id === r.dokterId);
  const totalQty = r.items.reduce((s, i) => s + i.qty, 0);
  const totalHarga = r.items.reduce((s, i) => {
    const obat = OBAT.find(o => o.sku === i.sku);
    return s + (obat ? obat.harga * i.qty : 0);
  }, 0);

  return (
    <div className={'resep-card ' + r.status}>
      <div className="row between" style={{marginBottom:10}}>
        <div>
          <div style={{fontSize:11, color:'hsl(var(--muted-foreground))', textTransform:'uppercase', letterSpacing:'0.06em', fontWeight:600}}>{r.id}</div>
          <div style={{fontSize:14, fontWeight:600, marginTop:2}}>{p.nama}</div>
          <div style={{fontSize:11.5, color:'hsl(var(--muted-foreground))', marginTop:2}}>
            {p.id} · {p.usia}th · Antrian {r.antrianNo}
          </div>
        </div>
        <StatusPill status={r.status}/>
      </div>

      <div style={{fontSize:12, color:'hsl(var(--muted-foreground))', marginBottom:8}}>
        Diresepkan oleh <b style={{color:'hsl(var(--foreground))'}}>{d.name}</b> · {d.spesialis}
      </div>

      {p.alergi !== '—' && (
        <div className="callout danger" style={{padding:'8px 10px', marginBottom:10}}>
          <Icon name="alert" size={13}/>
          <span style={{fontSize:12}}><b>Alergi:</b> {p.alergi}</span>
        </div>
      )}

      <div style={{padding:'8px 0', borderTop:'1px solid hsl(var(--border))', borderBottom:'1px solid hsl(var(--border))', marginBottom:10}}>
        {r.items.map((i, idx) => {
          const obat = OBAT.find(o => o.sku === i.sku);
          return (
            <div key={idx} className="resep-item">
              <div>
                <div className="resep-item-name">{obat?.nama || i.sku}</div>
                <div className="resep-item-sig">{i.sig}</div>
              </div>
              <div style={{fontVariantNumeric:'tabular-nums', fontSize:12.5}}>{i.qty}× {obat?.satuan}</div>
              <div style={{fontVariantNumeric:'tabular-nums', fontSize:12, color:'hsl(var(--muted-foreground))'}}>{rupiah(obat ? obat.harga * i.qty : 0, {sym:true})}</div>
            </div>
          );
        })}
      </div>

      <div className="row between" style={{fontSize:12.5, marginBottom:10}}>
        <div className="muted">Total {totalQty} item</div>
        <div style={{fontWeight:600, fontVariantNumeric:'tabular-nums'}}>{rupiah(totalHarga, {sym:true})}</div>
      </div>

      <div className="row gap-2">
        {r.status === 'pending' ? (
          <>
            <Btn icon="check" tone="primary" onClick={()=>pushToast({msg:`${r.id} di-dispense`})}>Dispense & Serahkan</Btn>
            <Btn icon="x" tone="ghost" size="sm">Tolak</Btn>
          </>
        ) : (
          <>
            <div style={{fontSize:11.5, color:'hsl(var(--muted-foreground))'}}>Diserahkan {r.issuedAt} WIB</div>
            <Btn icon="eye" tone="outline" size="sm" onClick={()=>pushToast({msg:'Detail dispensing'})}>Detail</Btn>
          </>
        )}
      </div>
    </div>
  );
}

window.Apotek = Apotek;
