import Link from 'next/link';
import { redirect } from 'next/navigation';
import { AdminShell } from '../../../components/admin/admin-page.jsx';
import { getCase } from '../../../../lib/process/engine.js';
import { getDefinition } from '../../../../lib/process/definitions.js';

export const dynamic = 'force-dynamic';

// Branded intake artifact page — the canonical "start a case" intake surface.
// Renders the case's intake-form artifact in a sandboxed iframe; the artifact
// ships its own form controls and POSTs directly to
// /api/processes/<id>/stages/<stage>/submit. The host page is chrome only.
//
// Reached from /workflows (Start) via /api/processes/start-and-route, or by
// deep link to a known case.
export default async function BrandedIntakePage({ params }) {
  const { caseId } = await params;
  const c = getCase(caseId);
  if (!c) redirect('/workflows');
  const definition = getDefinition(c.definition_id);
  const artifactId = c.context?.intake_form_artifact_id;
  const submitted = c.status !== 'intake';

  return (
    <AdminShell
      kicker="Workflows"
      title={c.title || 'Intake'}
      description={definition?.name || ''}
      actions={
        <Link href={`/workflows/${caseId}`} className="btn-secondary">View case</Link>
      }
    >
      <div className="branded-intake-host">
        {submitted ? (
          <div className="branded-intake-banner">
            <strong>Submitted.</strong> Intake is complete — the case is now <code>{c.status}</code>.
            <Link href={`/workflows/${caseId}`}>Open case ›</Link>
          </div>
        ) : null}
        {artifactId ? (
          <iframe
            title="Branded intake form"
            src={`/api/artifacts/${artifactId}/raw`}
            sandbox="allow-scripts allow-same-origin allow-forms"
            className="branded-intake-frame"
          />
        ) : (
          <p className="muted">
            No intake artifact was generated. Either the first stage is not an intake_form,
            or the artifact write failed (engine state is unaffected).{' '}
            <Link href={`/workflows/${caseId}`}>Open the case ›</Link>
          </p>
        )}
      </div>
    </AdminShell>
  );
}
