import Link from "next/link";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { db } from "@/lib/db";
import { Badge, btn, Card, Field, Logo, input } from "@/components/ui";
import { dateRange, parseJSON } from "@/lib/utils";
import { OnboardingSteps } from "../steps";
import { OAuthButtons } from "@/components/oauth-buttons";
import { getEnabledOAuthProviders } from "@/lib/oauth";
import { resendOnboardingCodeAction, sendOnboardingCodeAction, verifyOnboardingCodeAction } from "../actions";

export const metadata = { title: "Verify your email" };

export default async function VerifyPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string; sent?: string; resent?: string; edit?: string; dev?: string }>;
}) {
  const jar = await cookies();
  const token = jar.get("confexe_onboarding")?.value;
  const draft = token ? await db.onboardingDraft.findUnique({ where: { token } }) : null;
  if (!draft || draft.status === "COMPLETED") redirect("/start");

  const sp = await searchParams;
  const oauthProviders = await getEnabledOAuthProviders();
  const basics = parseJSON<{ name?: string; startAt?: string; endAt?: string; type?: string; city?: string; state?: string }>(draft.data, {});
  const codeStage = draft.status === "CODE_SENT" && !sp.edit;

  return (
    <main className="min-h-screen pb-16">
      <header className="mx-auto flex max-w-6xl items-center justify-between px-4 py-5">
        <Logo />
        <Link href="/start" className="text-sm text-zinc-500 hover:text-zinc-200">← Edit conference details</Link>
      </header>

      <div className="mx-auto max-w-xl px-4 text-center">
        <h1 className="fx-in text-3xl font-extrabold tracking-tight text-zinc-50">Almost there 🎉</h1>
        <p className="fx-in fx-d1 mt-2 text-zinc-400">
          {codeStage ? "Enter the 6-digit code we emailed you — then your dashboard opens." : "Verify your email to claim your conference. No password needed today."}
        </p>
        <div className="mt-6"><OnboardingSteps active={2} /></div>

        {/* What they're claiming */}
        <Card className="fx-in fx-d2 mt-8 flex flex-wrap items-center justify-center gap-x-4 gap-y-1 px-5 py-3.5 text-sm">
          <span className="font-bold text-zinc-100">{basics.name}</span>
          {basics.startAt && basics.endAt && <span className="text-zinc-500">📅 {dateRange(basics.startAt, basics.endAt)}</span>}
          {(basics.city || basics.state) && <span className="text-zinc-500">📍 {[basics.city, basics.state].filter(Boolean).join(", ")}</span>}
          <Badge className="bg-zinc-500/10 text-zinc-500">DRAFT — private until you publish</Badge>
        </Card>

        {sp.error && <p className="fx-in mt-5 rounded-xl bg-red-500/10 px-4 py-2.5 text-sm font-medium text-red-600">{sp.error}</p>}
        {sp.resent && <p className="fx-in mt-5 rounded-xl bg-emerald-500/10 px-4 py-2.5 text-sm font-medium text-emerald-600">✓ A fresh code is on its way.</p>}
        {sp.dev && (
          <p className="fx-in mt-5 rounded-xl bg-amber-500/10 px-4 py-2.5 text-sm font-medium text-amber-700">
            ⚠️ Dev mode (email not configured): your code is <code className="font-mono font-bold">{sp.dev}</code>
          </p>
        )}

        {!codeStage ? (
          <Card className="fx-in fx-d3 mt-6 p-6 text-left sm:p-8">
            <form action={sendOnboardingCodeAction} className="space-y-4">
              <Field name="email" title="Work email *">
                <input id="email" name="email" type="email" required autoFocus defaultValue={draft.email ?? ""} placeholder="you@organization.org" className={`${input} py-3 text-base`} />
              </Field>
              <div className="grid gap-4 sm:grid-cols-2">
                <Field name="name" title="Your name *">
                  <input id="name" name="name" required defaultValue={draft.name ?? ""} placeholder="Full name" className={input} />
                </Field>
                <Field name="orgName" title="Organization (optional)">
                  <input id="orgName" name="orgName" defaultValue={draft.orgName ?? ""} placeholder="Company, institute, community…" className={input} />
                </Field>
              </div>
              <button className={`${btn.primary} w-full py-3 text-base`}>Email me a verification code →</button>
              <p className="text-center text-xs text-zinc-600">
                No password, no forms — just prove the inbox is yours and you're in.
              </p>
            </form>
          </Card>
        ) : (
          <Card className="fx-in fx-d3 mt-6 p-6 text-left sm:p-8">
            <p className="text-center text-sm text-zinc-400">
              Code sent to <b className="text-zinc-200">{draft.email}</b>
            </p>
            <form action={verifyOnboardingCodeAction} className="mt-4 space-y-4">
              <input
                id="code"
                name="code"
                inputMode="numeric"
                pattern="[0-9]*"
                maxLength={6}
                minLength={6}
                required
                autoFocus
                autoComplete="one-time-code"
                placeholder="● ● ● ● ● ●"
                className={`${input} py-4 text-center text-2xl font-extrabold tracking-[0.5em]`}
              />
              <button className={`${btn.primary} w-full py-3 text-base`}>Verify & open my dashboard →</button>
            </form>
            <div className="mt-4 flex items-center justify-center gap-4 text-xs">
              <form action={resendOnboardingCodeAction}>
                <button className="font-semibold text-indigo-600 hover:underline">Resend code</button>
              </form>
              <span className="text-zinc-600">·</span>
              <Link href="/start/verify?edit=1" className="text-zinc-500 hover:text-zinc-200">Change email</Link>
            </div>
          </Card>
        )}

        {oauthProviders.length > 0 && (
          <div className="fx-in fx-d4 mx-auto mt-2 max-w-md text-left">
            <OAuthButtons providers={oauthProviders} role="organizer" verb="Continue" />
            <p className="mt-2 text-center text-[11px] text-zinc-600">Signing in with Google or LinkedIn verifies your email instantly and opens your dashboard — no code needed.</p>
          </div>
        )}

        <p className="mt-6 text-xs text-zinc-600">
          Already have an account? <Link href="/login" className="font-semibold text-indigo-600 hover:underline">Sign in</Link> — or just verify with the same email and we'll attach the conference to it.
        </p>
      </div>
    </main>
  );
}
