import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { AdminShell, EmptyState, StatCard, StatusPill } from '@/app/components/admin/admin-page.jsx';
import { decideApprovalRequest, listApprovalRequests } from '@/lib/approvals.js';
import { listAudit } from '@/lib/runtime.js';

export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';

async function decideAction(formData) {
  'use server';
  decideApprovalRequest(String(formData.get('id')), String(formData.get('decision')), { approved_by: 'owner' });
  revalidatePath('/approvals');
  redirect('/approvals');
}

function riskTone(risk) {
  if (risk === 'high') return 'danger';
  if (risk === 'medium') return 'warn';
  return 'ready';
}

export default function ApprovalsPage() {
  const approvals = listApprovalRequests({ limit: 100 });
  const pending = approvals.filter(approval => approval.status === 'pending');
  const audit = listAudit(12);

  return (
    <AdminShell
      title="Approvals"
      description="madarX OS v1.0 approval queue and decision history for human-in-loop actions, with payload, risk, and linked audit context."
    >
      <section className="admin-stats">
        <StatCard label="Pending approvals" value={pending.length} tone="mars" />
        <StatCard label="Total requests" value={approvals.length} />
        <StatCard label="Audit context rows" value={audit.length} />
      </section>

      <section className="admin-grid approvals-layout">
        <div className="admin-panel">
          <div className="admin-panel-head">
            <span>Pending queue</span>
            <small>Approve or deny only after reviewing risk and payload preview.</small>
          </div>
          {pending.length ? (
            <div className="admin-card-list">
              {pending.map(approval => (
                <article className="admin-record" key={approval.id}>
                  <div className="admin-record-top">
                    <b>{approval.summary}</b>
                    <StatusPill tone={riskTone(approval.risk)}>Risk {approval.risk || 'medium'}</StatusPill>
                  </div>
                  <p>{approval.action_type} · requested by {approval.requested_by || 'system'} · {approval.created_at}</p>
                  <pre>{JSON.stringify(approval.payload || {}, null, 2)}</pre>
                  <form className="admin-inline-actions" action={decideAction}>
                    <input type="hidden" name="id" value={approval.id} />
                    <button className="admin-button" name="decision" value="approved" type="submit">Approve</button>
                    <button className="admin-button secondary" name="decision" value="denied" type="submit">Deny</button>
                  </form>
                </article>
              ))}
            </div>
          ) : <EmptyState title="No pending approvals">Approval-gated tool and run requests will appear here.</EmptyState>}
        </div>

        <div className="admin-panel">
          <div className="admin-panel-head">
            <span>Linked status / audit context</span>
            <small>Recent approval and runtime audit entries.</small>
          </div>
          <div className="admin-card-list compact">
            {audit.map(row => (
              <article className="admin-record compact" key={row.id}>
                <div className="admin-record-top"><b>{row.type}</b><StatusPill>{row.status || 'logged'}</StatusPill></div>
                <p>{row.summary}</p>
                <small>{row.at}</small>
              </article>
            ))}
          </div>
        </div>
      </section>

      <section className="admin-panel">
        <div className="admin-panel-head">
          <span>Approval history</span>
          <small>Queue and history in one operator view.</small>
        </div>
        {approvals.length ? (
          <div className="admin-table-wrap">
            <table className="admin-table">
              <thead><tr><th>Request</th><th>Status</th><th>Risk</th><th>Requested</th><th>Decided</th></tr></thead>
              <tbody>
                {approvals.map(approval => (
                  <tr key={approval.id}>
                    <td><b>{approval.summary}</b><small>{approval.id} · {approval.action_type}</small></td>
                    <td><StatusPill tone={approval.status === 'pending' ? 'warn' : approval.status === 'approved' ? 'ready' : 'neutral'}>{approval.status}</StatusPill></td>
                    <td><StatusPill tone={riskTone(approval.risk)}>{approval.risk}</StatusPill></td>
                    <td>{approval.created_at}<small>{approval.requested_by}</small></td>
                    <td>{approval.decided_at || 'not decided'}<small>{approval.approved_by || '—'}</small></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : <EmptyState title="No approval history">Approval requests will be captured with audit records.</EmptyState>}
      </section>
    </AdminShell>
  );
}
