import Link from "next/link";
import { auth, unstable_update } from "@/core/auth/auth";
import { confirmEmailChange, AccountError } from "@/services/account-service";

type SearchParams = Promise<{
  token?: string | string[];
  uid?: string | string[];
}>;

function first(value: string | string[] | undefined): string {
  if (Array.isArray(value)) return value[0] ?? "";
  return value ?? "";
}

export default async function VerifyEmailPage({
  searchParams,
}: {
  searchParams: SearchParams;
}) {
  const params = await searchParams;
  const token = first(params.token).trim();
  const uid = first(params.uid).trim();

  let state: "ok" | "error" = "error";
  let message = "This verification link is invalid or incomplete.";
  let email: string | null = null;

  if (token && uid) {
    try {
      const account = await confirmEmailChange(uid, token);
      state = "ok";
      email = account.email;
      message = "Your login email has been updated and verified.";

      const session = await auth();
      if (session?.user?.id === uid) {
        await unstable_update({
          user: {
            name: account.name,
            email: account.email,
          },
        });
      }
    } catch (error) {
      if (error instanceof AccountError) {
        message = error.message;
      } else {
        message = "Unable to verify this email right now.";
      }
    }
  }

  return (
    <main className="min-h-dvh bg-[var(--archi-cream)] text-[var(--archi-ink)]">
      <div className="mx-auto flex min-h-dvh w-full max-w-lg flex-col justify-center px-6 py-16">
        <p className="text-[0.65rem] tracking-[0.28em] text-[var(--archi-ink-muted)] uppercase">
          Account
        </p>
        <h1 className="mt-3 font-[family-name:var(--font-display)] text-3xl tracking-tight sm:text-4xl">
          {state === "ok" ? "Email verified" : "Verification failed"}
        </h1>
        <p className="mt-4 text-base leading-7 text-[var(--archi-ink-muted)]">
          {message}
        </p>
        {email ? (
          <p className="mt-3 text-sm font-medium text-[var(--archi-ink)]">
            Active login: {email}
          </p>
        ) : null}
        <div className="mt-10 flex flex-wrap gap-3">
          <Link href="/dashboard/settings" className="studio-btn-primary">
            Back to settings
          </Link>
          <Link href="/?auth=login" className="studio-btn-ghost">
            Sign in
          </Link>
        </div>
      </div>
    </main>
  );
}
