"use client";

import { Suspense } from "react";
import Link from "next/link";
import { Loader2 } from "lucide-react";

import { AuthFormWrapper } from "@/components/forms/auth-form-wrapper";
import { KratosFlowForm } from "@/components/auth/kratos-flow-form";
import { KratosMessages } from "@/components/auth/kratos-messages";
import { useKratosFlow } from "@/lib/kratos/use-kratos-flow";
import type { KratosFlow } from "@/lib/kratos";

// ---------------------------------------------------------------------------
// Verify email — Ory Kratos `verification` browser self-service flow
// ---------------------------------------------------------------------------
// Like recovery, the verification flow is single-page and multi-step: the user
// submits their email, Kratos sends a code and re-renders the flow with a
// "code" input. A valid code marks the address verified. Kratos keeps the flow
// in `state: "passed_challenge"` and shows a success message — there is no
// session change, so we leave the user on the page.
// ---------------------------------------------------------------------------

function VerifyEmailForm() {
  const { flow, loading, error, setFlow } = useKratosFlow("verification");

  function handleResult(result: { status: number; ok: boolean; data: unknown }) {
    // Kratos returns the same flow re-rendered for every step (email -> code,
    // and the final "passed_challenge" success). Just re-render it.
    if (result.data && typeof result.data === "object" && "ui" in result.data) {
      setFlow(result.data as KratosFlow);
    }
  }

  const verified = flow?.state === "passed_challenge";

  return (
    <AuthFormWrapper
      title="Verify your email"
      subtitle={
        verified
          ? "Your email has been verified."
          : "Enter your email, then the code we send you"
      }
      footer={
        <p>
          <Link href="/login" className="text-primary hover:underline">
            Back to login
          </Link>
        </p>
      }
    >
      <div className="flex flex-col gap-4">
        <KratosMessages flow={flow} error={error} />

        {loading && !flow && (
          <div className="flex items-center justify-center py-6 text-muted-foreground">
            <Loader2 className="animate-spin" />
          </div>
        )}

        {flow && !verified && (
          <KratosFlowForm flow={flow} onResult={handleResult} />
        )}
      </div>
    </AuthFormWrapper>
  );
}

export default function VerifyEmailPage() {
  return (
    <Suspense>
      <VerifyEmailForm />
    </Suspense>
  );
}
