// Payroll Run — draft validation and approval
const { useState: useStatePR } = React;

function PayrollRun({ dept, role, setPage, pushToast }) {
  const [tab, setTab] = useStatePR('summary');
  const employees = dept === 'all' ? KARYAWAN : KARYAWAN.filter(k => k.deptId === dept);
  const slips = employees.map(k => slipGaji(k.id));
  const totalPenghasilan = slips.reduce((s, sl) => s + sl.penghasilan.total, 0);
  const totalPotongan = slips.reduce((s, sl) => s + sl.potongan.total, 0);
  const totalTHP = slips.reduce((s, sl) => s + sl.takeHome, 0);
  const exceptions = slips.filter(sl => !sl.karyawan.npwp || sl.absensi.alpha > 0 || sl.potongan.pinjaman > 0);

  return (
    <>
      <PageHeader
        eyebrow={`Draft ${PERIODE_LABEL} · Run ${formatDateID(NEXT_PAYROLL)}`}
        title="Payroll Run"
        subtitle={`Draft payroll untuk ${employees.length} karyawan. Total THP ${rupiah(totalTHP, {sym:true})}; ${exceptions.length} exception perlu review sebelum approval finance.`}
        actions={<>
          <Btn icon="check" tone="primary" onClick={()=>pushToast({msg:'Draft payroll disubmit ke Finance'})}>Submit Finance</Btn>
          <Btn icon="refresh" tone="outline" onClick={()=>pushToast({msg:'Payroll dihitung ulang dari absensi terbaru'})}>Recalculate</Btn>
          <Btn icon="receipt" tone="outline" onClick={()=>setPage('slip')}>Preview Slip</Btn>
        </>}
      />

      <Card className="payroll-run-card" style={{marginBottom:18}}>
        <div className="row between" style={{alignItems:'flex-start', gap:18}}>
          <div>
            <div style={{fontSize:11, color:'hsl(var(--muted-foreground))', textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:800}}>Payroll Batch</div>
            <div style={{fontSize:24, fontWeight:800, letterSpacing:'-0.03em', marginTop:4}}>PR-2026-04 · {PERIODE_LABEL}</div>
            <div className="payroll-run-total" style={{marginTop:10}}>{rupiah(totalTHP, {sym:true, compact:true})}</div>
            <div className="text-sm muted" style={{marginTop:4}}>{employees.length} karyawan · diproses sebagai {ROLES[role].role}</div>
          </div>
          <StatusPill status="draft" />
        </div>
        <div className="payroll-stepper">
          <div className="payroll-step done"><div className="payroll-step-title">1. Data</div><div className="payroll-step-sub">Karyawan + bank</div></div>
          <div className="payroll-step done"><div className="payroll-step-title">2. Absensi</div><div className="payroll-step-sub">Cuti/lembur masuk</div></div>
          <div className="payroll-step active"><div className="payroll-step-title">3. Validasi</div><div className="payroll-step-sub">{exceptions.length} exception</div></div>
          <div className="payroll-step"><div className="payroll-step-title">4. Transfer</div><div className="payroll-step-sub">Mandiri CMS</div></div>
        </div>
      </Card>

      <div className="grid g-4" style={{marginBottom:18}}>
        <Kpi label="Total Penghasilan" value={rupiah(totalPenghasilan, {sym:true, compact:true})} sub="Gaji + tunjangan + lembur" icon="arrowUp" tone="green" />
        <Kpi label="Total Potongan" value={rupiah(totalPotongan, {sym:true, compact:true})} sub="BPJS, PPh21, pinjaman" icon="arrowDown" tone="rose" />
        <Kpi label="Take Home Pay" value={rupiah(totalTHP, {sym:true, compact:true})} sub="Siap transfer setelah approval" icon="creditCard" tone="accent" />
        <Kpi label="Exception" value={exceptions.length} sub="NPWP, alpha, pinjaman" icon="alert" tone="amber" />
      </div>

      <div className="row gap-2" style={{marginBottom:14}}>
        {[
          {id:'summary', label:'Summary'},
          {id:'components', label:'Komponen'},
          {id:'exceptions', label:'Exception'},
          {id:'history', label:'Run History'},
        ].map(t => <button key={t.id} onClick={()=>setTab(t.id)} className={'btn ' + (tab === t.id ? '' : 'outline') + ' sm'}>{t.label}</button>)}
      </div>

      {tab === 'summary' && <PayrollSummary slips={slips} />}
      {tab === 'components' && <PayrollComponents slips={slips} />}
      {tab === 'exceptions' && <PayrollExceptions exceptions={exceptions} pushToast={pushToast} />}
      {tab === 'history' && <PayrollHistory />}
    </>
  );
}

function PayrollSummary({ slips }) {
  const byDept = DEPT.map(d => {
    const deptSlips = slips.filter(sl => sl.karyawan.deptId === d.id);
    return {
      dept: d.name,
      count: deptSlips.length,
      total: deptSlips.reduce((s, sl) => s + sl.takeHome, 0),
    };
  }).filter(d => d.count > 0).sort((a,b) => b.total - a.total);
  const max = Math.max(...byDept.map(d => d.total));
  return (
    <Card>
      <div style={{padding:'14px 16px', borderBottom:'1px solid hsl(var(--border))'}}><SectionHead title="Summary per Departemen" hint="THP April 2026" /></div>
      <div style={{padding:'16px'}}>
        <div className="grid g-3">
          {byDept.map(d => (
            <div key={d.dept} className="dept-card">
              <div className="row between"><div style={{fontWeight:800}}>{d.dept}</div><SoftPill color="indigo">{d.count} org</SoftPill></div>
              <div style={{fontSize:20, fontWeight:800, marginTop:8, fontVariantNumeric:'tabular-nums'}}>{rupiah(d.total, {sym:true, compact:true})}</div>
              <div className="dept-bar"><div style={{width:(d.total / max) * 100 + '%'}} /></div>
            </div>
          ))}
        </div>
      </div>
    </Card>
  );
}

function PayrollComponents({ slips }) {
  return (
    <Card>
      <div style={{padding:'14px 16px', borderBottom:'1px solid hsl(var(--border))'}}><SectionHead title="Detail Komponen Payroll" hint={`${slips.length} slip dalam batch`} /></div>
      <div style={{maxHeight:'58vh', overflowY:'auto'}}>
        <table className="table">
          <thead style={{position:'sticky', top:0, background:'hsl(var(--card))', zIndex:1}}>
            <tr><th>Karyawan</th><th>Dept</th><th style={{textAlign:'right'}}>Penghasilan</th><th style={{textAlign:'right'}}>BPJS</th><th style={{textAlign:'right'}}>PPh21</th><th style={{textAlign:'right'}}>Potongan</th><th style={{textAlign:'right'}}>THP</th></tr>
          </thead>
          <tbody>
            {slips.map(sl => (
              <tr key={sl.karyawan.id}>
                <td><div style={{fontWeight:700}}>{sl.karyawan.nama}</div><div className="mono text-sm muted">{sl.karyawan.id}</div></td>
                <td className="text-sm">{sl.karyawan.dept}</td>
                <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums'}}>{rupiah(sl.penghasilan.total, {sym:true})}</td>
                <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums'}}>{rupiah(sl.potongan.bpjsKes + sl.potongan.bpjsJht + sl.potongan.bpjsJp, {sym:true})}</td>
                <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums'}}>{rupiah(sl.potongan.pph21, {sym:true})}</td>
                <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums'}}>{rupiah(sl.potongan.total, {sym:true})}</td>
                <td style={{textAlign:'right', fontWeight:800, fontVariantNumeric:'tabular-nums'}}>{rupiah(sl.takeHome, {sym:true})}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </Card>
  );
}

function PayrollExceptions({ exceptions, pushToast }) {
  return (
    <Card>
      <div style={{padding:'14px 16px', borderBottom:'1px solid hsl(var(--border))'}}><SectionHead title="Exception Payroll" hint="Harus direview sebelum submit finance" /></div>
      <div style={{padding:'14px 16px', display:'flex', flexDirection:'column', gap:10}}>
        {exceptions.map(sl => (
          <div key={sl.karyawan.id} className="callout warn">
            <Icon name="alert" size={14}/>
            <div style={{flex:1}}>
              <div style={{fontWeight:800}}>{sl.karyawan.nama} · {sl.karyawan.id}</div>
              <div className="text-sm" style={{marginTop:3}}>
                {!sl.karyawan.npwp && 'NPWP belum ada. '}
                {sl.absensi.alpha > 0 && `${sl.absensi.alpha} alpha periode ini. `}
                {sl.potongan.pinjaman > 0 && `Potongan pinjaman ${rupiah(sl.potongan.pinjaman, {sym:true})}.`}
              </div>
            </div>
            <Btn icon="check" tone="outline" onClick={()=>pushToast({msg:`Exception ${sl.karyawan.id} ditandai OK`})}>Mark OK</Btn>
          </div>
        ))}
      </div>
    </Card>
  );
}

function PayrollHistory() {
  return (
    <Card>
      <div style={{padding:'14px 16px', borderBottom:'1px solid hsl(var(--border))'}}><SectionHead title="Riwayat Payroll Run" hint="5 periode terakhir" /></div>
      <table className="table">
        <thead><tr><th>Run ID</th><th>Periode</th><th>Status</th><th>Processed By</th><th>Tanggal</th><th style={{textAlign:'right'}}>Karyawan</th><th style={{textAlign:'right'}}>Total</th></tr></thead>
        <tbody>
          {PAYROLL_RUNS.map(r => (
            <tr key={r.id}>
              <td className="mono">{r.id}</td><td>{r.label}</td><td><StatusPill status={r.status}/></td><td>{r.processedBy || '-'}</td><td>{r.runDate ? formatDateID(r.runDate) : '-'}</td><td style={{textAlign:'right'}}>{r.karyawan}</td><td style={{textAlign:'right', fontWeight:800}}>{rupiah(r.total, {sym:true})}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  );
}

window.PayrollRun = PayrollRun;
