import { revalidatePath } from 'next/cache';
import { AdminShell, EmptyState, StatCard, StatusPill } from '../components/admin/admin-page.jsx';
import { listMissions, runMission } from '../../lib/missions.js';

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

async function runMissionAction(formData) {
  'use server';
  const slug = String(formData.get('slug') || '');
  const projectId = String(formData.get('project_id') || 'personal');
  if (slug) runMission(slug, projectId);
  revalidatePath('/missions');
}

const STATUS_TONES = {
  complete: 'ready',
  queued: 'neutral',
  running: 'warn',
  error: 'danger',
};

export default function MissionsPage() {
  const { templates, runs } = listMissions('personal');

  return (
    <AdminShell
      kicker="Missions"
      title="Mission templates"
      description="Repeatable, role-targeted work routed through the right installed agent."
    >
      <section className="admin-stats">
        <StatCard label="Templates" value={templates.length} />
        <StatCard label="Total runs" value={runs.length} />
        <StatCard
          label="Queued"
          value={runs.filter((r) => r.status === 'queued').length}
        />
        <StatCard
          label="Complete"
          value={runs.filter((r) => r.status === 'complete').length}
          tone="mars"
        />
      </section>

      <section className="mission-grid" data-page="missions">
        {templates.map((t) => (
          <article className="mission-card admin-record" key={t.slug}>
            <div className="admin-record-top">
              <div>
                <span className="panel-label">{t.target_role.replace(/_/g, ' ')}</span>
                <b>{t.name}</b>
              </div>
              <span className="mission-slug">{t.slug}</span>
            </div>
            <p>{t.prompt}</p>
            <div className="mission-card-foot">
              <small>{t.cadence}</small>
              <form action={runMissionAction}>
                <input type="hidden" name="slug" value={t.slug} />
                <input type="hidden" name="project_id" value="personal" />
                <button type="submit" className="admin-button">
                  Run
                </button>
              </form>
            </div>
          </article>
        ))}
      </section>

      <section className="admin-panel">
        <div className="admin-panel-head">
          <span>Recent runs</span>
          <small>The most recent 50 mission runs across all projects.</small>
        </div>
        {runs.length ? (
          <div className="admin-card-list compact">
            {runs.map((r) => (
              <div className="admin-record compact" key={r.id}>
                <div className="admin-record-top">
                  <div>
                    <b>{r.slug}</b>
                    <small className="mission-run-id">{r.id}</small>
                  </div>
                  <StatusPill tone={STATUS_TONES[r.status] || 'neutral'}>
                    {r.status}
                  </StatusPill>
                </div>
                {r.error ? <p className="admin-alert-text">{r.error}</p> : null}
              </div>
            ))}
          </div>
        ) : (
          <EmptyState title="No runs yet">
            Trigger a mission template above to queue your first run.
          </EmptyState>
        )}
      </section>
    </AdminShell>
  );
}
