// Official RAPBS versus Accounting realization report.
const { useState: useState$budgetReport } = React;

function BudgetVariancePill({ row }) {
  if (row.budget <= 0 && row.actual !== 0) return <Pill tone="danger">Tanpa anggaran</Pill>;
  if (row.type === 'income') {
    if (row.actual > row.budget) return <Pill tone="accent">Melebihi target</Pill>;
    if (row.actual >= row.budget) return <Pill tone="ok">Target tercapai</Pill>;
    return <Pill tone="warning">Belum tercapai</Pill>;
  }
  if (row.actual > row.budget) return <Pill tone="danger">Over budget</Pill>;
  if (row.percentage != null && row.percentage >= 80) return <Pill tone="warning">Mendekati batas</Pill>;
  return <Pill tone="ok">Aman</Pill>;
}

function BudgetComparisonSection({ type, rows, expandedId, setExpandedId }) {
  const meta = RAPBS_TYPE_META[type];
  const typeRows = rows.filter(row => row.type === type);
  const categories = [...new Map(typeRows.map(row => [row.category?.id || 'uncategorized', row.category || { id: 'uncategorized', name: 'Tanpa Kategori' }])).values()];

  return (
    <div className={'budget-comparison-section ' + type}>
      <div className="budget-comparison-section-head">
        <span className="rapbs-plan-section-icon"><Icon name={type === 'income' ? 'arrowRight' : 'expense'} size={17} /></span>
        <div><h2>{meta.label}</h2><p>{type === 'income' ? 'Capaian target penerimaan sekolah' : 'Penyerapan anggaran belanja sekolah'}</p></div>
      </div>
      {categories.map(category => {
        const categoryRows = typeRows.filter(row => (row.category?.id || 'uncategorized') === category.id);
        const subtotalBudget = categoryRows.reduce((sum, row) => sum + row.budget, 0);
        const subtotalActual = categoryRows.reduce((sum, row) => sum + row.actual, 0);
        return (
          <Card className="budget-comparison-card" key={category.id}>
            <div className="budget-comparison-category-head">
              <div><strong>{category.name}</strong><span>{categoryRows.length} Budget Item</span></div>
              <div><span>RAPBS</span><strong>{rupiah(subtotalBudget, { sym: true })}</strong></div>
              <div><span>Actual</span><strong>{rupiah(subtotalActual, { sym: true })}</strong></div>
            </div>
            <div className="table-wrap">
              <table className="table budget-comparison-table">
                <thead><tr><th></th><th>Budget Item / COA</th><th className="num">RAPBS</th><th className="num">Actual</th><th className="num">Remaining</th><th>Realisasi</th><th>Status</th></tr></thead>
                <tbody>
                  {categoryRows.map(row => {
                    const expanded = expandedId === row.id;
                    const progress = row.percentage == null ? 0 : Math.min(Math.max(row.percentage, 0), 100);
                    return (
                      <React.Fragment key={row.id}>
                        <tr>
                          <td><button className="budget-expand-button" aria-label={`${expanded ? 'Tutup' : 'Buka'} detail ${row.name}`} onClick={() => setExpandedId(expanded ? null : row.id)}><Icon name={expanded ? 'chevronDown' : 'chevronRight'} size={14} /></button></td>
                          <td><strong>{row.name}</strong><small><span className="code">{row.coaCode}</span> · {ACC[row.coaCode]?.name}</small></td>
                          <td className="num tnum">{rupiah(row.budget, { sym: true })}</td>
                          <td className="num tnum"><strong>{rupiah(row.actual, { sym: true })}</strong></td>
                          <td className={'num tnum ' + (row.remaining < 0 && type === 'outcome' ? 'budget-negative' : '')}>{rupiah(row.remaining, { sym: true })}</td>
                          <td><div className="budget-achievement"><span>{row.percentage == null ? '—' : `${row.percentage.toFixed(1)}%`}</span><div className="progress"><div className={'progress-bar' + (type === 'outcome' && row.actual > row.budget ? ' destructive' : '')} style={{width: progress + '%'}} /></div></div></td>
                          <td><BudgetVariancePill row={row} /></td>
                        </tr>
                        {expanded && (
                          <tr className="budget-detail-row"><td></td><td colSpan="6">
                            <div className="budget-detail-wrap">
                              <div className="budget-detail-title"><strong>Jurnal Pembentuk Actual</strong><span>{row.lines.length} baris · {rupiah(row.actual, { sym: true })}</span></div>
                              {row.lines.length === 0 ? <div className="empty">Belum ada jurnal posted untuk item ini.</div> : (
                                <table className="table budget-detail-table"><thead><tr><th>Tanggal</th><th>No. Jurnal</th><th>Keterangan</th><th className="num">Debit</th><th className="num">Kredit</th><th className="num">Actual</th></tr></thead><tbody>{row.lines.map(line => <tr key={line.id}><td>{formatDateID(line.date)}</td><td className="code">{line.journalId}</td><td>{line.desc}</td><td className="num tnum">{line.debit ? rupiah(line.debit) : '—'}</td><td className="num tnum">{line.credit ? rupiah(line.credit) : '—'}</td><td className={'num tnum ' + (line.amount < 0 ? 'budget-negative' : '')}>{rupiah(line.amount, { sym: true })}</td></tr>)}</tbody></table>
                              )}
                            </div>
                          </td></tr>
                        )}
                      </React.Fragment>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </Card>
        );
      })}
    </div>
  );
}

function UnbudgetedActualTable({ lines }) {
  const total = lines.reduce((sum, line) => sum + line.amount, 0);
  return (
    <Card className="budget-unbudgeted-card">
      <div className="card-header"><div><div className="card-title">Realisasi di Luar RAPBS</div><div className="card-desc">Jurnal posted pada COA yang tidak menjadi Budget Item aktif.</div></div><div className="budget-unbudgeted-total"><span>Total</span><strong>{rupiah(total, { sym: true })}</strong></div></div>
      <div className="card-body flush"><div className="table-wrap"><table className="table budget-unbudgeted-table"><thead><tr><th>Tanggal</th><th>No. Jurnal</th><th>Jenis</th><th>Akun</th><th>Keterangan</th><th className="num">Actual</th></tr></thead><tbody>
        {lines.length === 0 && <tr><td colSpan="6" className="empty">Tidak ada transaksi di luar RAPBS.</td></tr>}
        {lines.map(line => <tr key={line.id}><td>{formatDateID(line.date)}</td><td className="code">{line.journalId}</td><td><Pill tone={line.type === 'income' ? 'ok' : 'warning'}>{line.type === 'income' ? 'Pemasukan' : 'Pengeluaran'}</Pill></td><td><span className="code">{line.code}</span><small>{line.accountName}</small></td><td>{line.desc}</td><td className="num tnum"><strong>{rupiah(line.amount, { sym: true })}</strong></td></tr>)}
      </tbody><tfoot><tr><td colSpan="5"><strong>Total di luar RAPBS</strong></td><td className="num tnum"><strong>{rupiah(total, { sym: true })}</strong></td></tr></tfoot></table></div></div>
    </Card>
  );
}

function RapbsActualReport() {
  const store = useBudgetStore();
  const approvedYears = store.academicYears.filter(academicYear => academicYear.status === 'approved');
  const initialYearId = store.selectedAcademicYearId || approvedYears[0]?.id || store.academicYears[0]?.id || '';
  const [academicYearId, setAcademicYearId] = useState$budgetReport(initialYearId);
  const [view, setView] = useState$budgetReport('income');
  const [expandedId, setExpandedId] = useState$budgetReport(null);
  const academicYear = store.academicYears.find(value => value.id === academicYearId) || null;
  const comparison = academicYear ? rapbsActualComparison(store, store.journals, academicYear.id) : null;
  const official = academicYear?.status === 'approved';

  if (!academicYear) return <div className="empty">Belum ada Tahun Ajaran.</div>;

  return (
    <div className="budget-report-page col gap-4">
      <div className="budget-report-heading">
        <div><div className="budget-report-title-row"><h1>RAPBS vs Realisasi</h1>{official && <Pill tone="ok">Laporan Resmi</Pill>}</div><p className="lede">Perbandingan rencana approved dengan jurnal Accounting posted selama Juli–Juni.</p></div>
        <div className="budget-report-actions"><label className="rapbs-year-picker"><span>Tahun Ajaran</span><select value={academicYearId} onChange={event => { setAcademicYearId(event.target.value); setExpandedId(null); }}>{store.academicYears.map(value => <option value={value.id} key={value.id}>{value.name} · {RAPBS_APPROVAL_META[value.status].label}</option>)}</select></label>{official && <><Btn icon="download">Ekspor</Btn><Btn icon="print" onClick={() => window.print()}>Cetak</Btn></>}</div>
      </div>

      {!official ? (
        <div className="budget-report-locked"><span><Icon name="clock" size={24} /></span><div><h2>RAPBS belum disetujui</h2><p>Perbandingan resmi hanya tersedia untuk RAPBS berstatus Disetujui. Tahun Ajaran {academicYear.name} saat ini berstatus {RAPBS_APPROVAL_META[academicYear.status].label}.</p></div></div>
      ) : (
        <>
          <div className="budget-report-period"><Icon name="calendar" size={15} /><span>Periode laporan</span><strong>1 Juli {academicYear.startYear} – 30 Juni {academicYear.endYear}</strong><Pill tone="ok">Approved</Pill></div>
          <div className="budget-report-summary-grid">
            <div className="budget-report-summary income"><span>Target Pendapatan</span><strong>{rupiah(comparison.income.budget, { sym: true })}</strong><small>Actual total {rupiah(comparison.income.totalActual, { sym: true })}</small></div>
            <div className="budget-report-summary outcome"><span>Anggaran Belanja</span><strong>{rupiah(comparison.outcome.budget, { sym: true })}</strong><small>Actual total {rupiah(comparison.outcome.totalActual, { sym: true })}</small></div>
            <div className="budget-report-summary net"><span>Surplus / Defisit Actual</span><strong>{rupiah(comparison.income.totalActual - comparison.outcome.totalActual, { sym: true })}</strong><small>Rencana {rupiah(comparison.income.budget - comparison.outcome.budget, { sym: true })}</small></div>
            <div className={'budget-report-summary ' + (comparison.unbudgeted.length ? 'unbudgeted' : '')}><span>Di Luar RAPBS</span><strong>{rupiah(comparison.income.unbudgetedActual + comparison.outcome.unbudgetedActual, { sym: true })}</strong><small>{comparison.unbudgeted.length} baris jurnal posted</small></div>
          </div>

          <div className="budget-report-breakdown">
            <div><span>Pendapatan terpetakan</span><strong>{rupiah(comparison.income.mappedActual, { sym: true })}</strong><small>{comparison.income.percentage?.toFixed(1) || '0,0'}% dari target</small></div>
            <div><span>Belanja terpetakan</span><strong>{rupiah(comparison.outcome.mappedActual, { sym: true })}</strong><small>{comparison.outcome.percentage?.toFixed(1) || '0,0'}% terserap</small></div>
            <div><span>Pemasukan tanpa anggaran</span><strong>{rupiah(comparison.income.unbudgetedActual, { sym: true })}</strong><small>{comparison.unbudgeted.filter(line => line.type === 'income').length} baris</small></div>
            <div><span>Pengeluaran tanpa anggaran</span><strong>{rupiah(comparison.outcome.unbudgetedActual, { sym: true })}</strong><small>{comparison.unbudgeted.filter(line => line.type === 'outcome').length} baris</small></div>
          </div>

          <div className="budget-report-tabs"><div className="tabs">{[['income', 'Pendapatan'], ['outcome', 'Belanja'], ['unbudgeted', `Di luar RAPBS (${comparison.unbudgeted.length})`]].map(([value, label]) => <button key={value} className={'tab' + (view === value ? ' active' : '')} onClick={() => { setView(value); setExpandedId(null); }}>{label}</button>)}</div><span>Actual hanya dari jurnal posted.</span></div>

          {view === 'income' && <BudgetComparisonSection type="income" rows={comparison.rows} expandedId={expandedId} setExpandedId={setExpandedId} />}
          {view === 'outcome' && <BudgetComparisonSection type="outcome" rows={comparison.rows} expandedId={expandedId} setExpandedId={setExpandedId} />}
          {view === 'unbudgeted' && <UnbudgetedActualTable lines={comparison.unbudgeted} />}
        </>
      )}
    </div>
  );
}

Object.assign(window, { BudgetVariancePill, BudgetComparisonSection, UnbudgetedActualTable, RapbsActualReport });
