import { redirect } from 'next/navigation';
import { getCase } from '../../../../lib/process/engine.js';
import { getDefinition } from '../../../../lib/process/definitions.js';
import { verifyShareToken } from '../../../../lib/share-token.js';
import { createIntakeFormArtifact } from '../../../../lib/process/artifacts.js';
import { getSettings as getDefinitionSettings, resolveBrandPresentation } from '../../../../lib/process/definition-settings.js';
import { getStage } from '../../../../lib/process/definitions.js';
import { getDb } from '../../../../lib/db.js';

export const dynamic = 'force-dynamic';

// Anonymous share-link landing page. The share URL embeds the token in
// `?token=…`. We:
//   1. Verify the token (HMAC + expiry + claims). Bad tokens → 404 message.
//   2. Look up the case and confirm it's still on the intake stage.
//   3. Render a TOKEN-AWARE branded artifact whose submit form posts with
//      the token in the body, then deliver the HTML directly (no auth shell).
//
// The chrome is intentionally absent — clients should never see the admin
// dashboard. The artifact is self-contained.
function parseIntakeFormSchema(definition) {
  if (!definition) return null;
  if (definition.intake_form_schema) return definition.intake_form_schema;
  return null;
}

export default async function ShareLinkPage({ params, searchParams }) {
  const { caseId } = await params;
  const sp = (await searchParams) || {};
  const token = typeof sp.token === 'string' ? sp.token : null;

  if (!token) return <ShareError reason="Missing token." />;
  const claims = verifyShareToken(token);
  if (!claims) return <ShareError reason="This link is invalid or has expired." />;
  if (claims.c !== caseId) return <ShareError reason="Token does not match this case." />;

  const c = getCase(caseId);
  if (!c) return <ShareError reason="Case not found." />;
  if (c.status !== 'intake') return <ShareError reason="Intake is already complete." />;
  const stage = getStage(c.current_stage_id);
  if (!stage || claims.s !== stage.id) return <ShareError reason="Stage mismatch." />;

  const definition = getDefinition(c.definition_id);
  const schema = parseIntakeFormSchema(definition);
  const settingsRow = getDefinitionSettings({ definition_id: c.definition_id, project_id: c.project_id });
  // For the share-link path we re-resolve the brand at render time so a
  // mid-flight global brand edit is reflected on the shared form. (The
  // dashboard host iframe uses the case snapshot, which is frozen — share
  // links are reissued on demand and conventionally short-lived, so live
  // resolution is the operator-friendlier default here.)
  const resolvedBrand = resolveBrandPresentation({ settings: settingsRow });
  const settings = { ...(settingsRow || {}), brand: resolvedBrand };

  const artifactId = createIntakeFormArtifact({
    definition,
    schema,
    caseRow: c,
    settings,
    submit_endpoint: `/api/processes/${c.id}/stages/${stage.slug}/submit`,
    submit_token: token,
  });

  if (!artifactId) return <ShareError reason="Could not render the form. Contact the sender." />;

  return (
    <iframe
      title="Intake form"
      src={`/api/artifacts/${artifactId}/raw`}
      sandbox="allow-scripts allow-same-origin allow-forms"
      style={{ width: '100vw', height: '100vh', border: 0, display: 'block' }}
    />
  );
}

function ShareError({ reason }) {
  return (
    <main style={{ maxWidth: 480, margin: '12vh auto', padding: '24px', font: '14px/1.5 ui-sans-serif, system-ui, sans-serif', textAlign: 'center' }}>
      <h1 style={{ fontSize: 22, margin: '0 0 8px' }}>Share link unavailable</h1>
      <p style={{ color: '#5f5a55', margin: 0 }}>{reason}</p>
      <p style={{ color: '#5f5a55', marginTop: 12, fontSize: 12 }}>If you need a new link, ask the sender to mint another.</p>
    </main>
  );
}
