import { OnboardingForm } from './OnboardingForm';

interface PublicOnboardInfo {
  groupName: string;
  tenantName: string;
  policyVersion: string;
  defaultScopes: string[];
  defaultRetentionDays: number;
}

export default async function OnboardPage({
  searchParams,
}: {
  searchParams: Promise<{ token?: string }>;
}) {
  const { token } = await searchParams;
  if (!token) {
    return (
      <div className="max-w-md mx-auto mt-12 p-6 rounded-lg border border-red-200 bg-red-50">
        <h1 className="text-lg font-semibold text-red-800">Invalid link</h1>
        <p className="text-sm text-red-700">This onboarding link is missing the token parameter.</p>
      </div>
    );
  }

  let info: PublicOnboardInfo | null = null;
  let error: string | null = null;
  try {
    const res = await fetch(
      `${process.env['API_URL'] ?? 'http://localhost:3001'}/public/onboard/${encodeURIComponent(token)}`,
      { headers: { Accept: 'application/json' }, cache: 'no-store' },
    );
    if (res.ok) {
      info = (await res.json()) as PublicOnboardInfo;
    } else {
      const body = (await res.json().catch(() => ({}))) as { message?: string };
      error = body.message ?? `Onboarding link rejected (${res.status})`;
    }
  } catch (e) {
    error = e instanceof Error ? e.message : 'Network error';
  }

  if (error || !info) {
    return (
      <div className="max-w-md mx-auto mt-12 p-6 rounded-lg border border-red-200 bg-red-50">
        <h1 className="text-lg font-semibold text-red-800">Cannot start onboarding</h1>
        <p className="text-sm text-red-700">{error ?? 'Unknown error'}</p>
      </div>
    );
  }

  return (
    <div className="max-w-md mx-auto mt-12 p-6 rounded-lg border border-gray-200 bg-white">
      <h1 className="text-xl font-semibold mb-2">Join {info.groupName}</h1>
      <p className="text-sm text-gray-600 mb-1">Managed by {info.tenantName}</p>
      <p className="text-xs text-gray-500 mb-4">
        Policy version: {info.policyVersion} · Default retention: {info.defaultRetentionDays} days
      </p>
      <OnboardingForm
        token={token}
        defaultScopes={info.defaultScopes}
        defaultRetentionDays={info.defaultRetentionDays}
      />
    </div>
  );
}
