"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 { trackEvent, AnalyticsEvents } from "@/lib/analytics";
import type { KratosFlow } from "@/lib/kratos";

// ---------------------------------------------------------------------------
// Registration — Ory Kratos `registration` browser self-service flow
// ---------------------------------------------------------------------------
// Kratos owns the schema (traits.email, traits.name.first, ...). The form is
// rendered entirely from `flow.ui.nodes`, so whatever the identity schema
// defines is what the user sees.
// ---------------------------------------------------------------------------

function RegisterForm() {
  const { flow, loading, error, setFlow } = useKratosFlow("registration");

  function handleResult(result: { status: number; ok: boolean; data: unknown }) {
    if (result.ok) {
      trackEvent(AnalyticsEvents.USER_REGISTERED, {
        method: "kratos",
        platform: "web",
      });
      // Depending on Kratos config, registration may either log the user in
      // immediately (session cookie set) or require email verification first.
      // `/app` works in both cases — middleware / whoami will route the user
      // to verification if a session is not yet active.
      window.location.href = "/app";
      return;
    }
    if (result.data && typeof result.data === "object" && "ui" in result.data) {
      setFlow(result.data as KratosFlow);
    }
  }

  return (
    <AuthFormWrapper
      title="Create account"
      subtitle="Get started with honeyDue"
      footer={
        <p>
          Already have an account?{" "}
          <Link href="/login" className="text-primary hover:underline">
            Sign in
          </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 && (
          <KratosFlowForm
            flow={flow}
            onResult={handleResult}
            submitLabel="Create account"
          />
        )}
      </div>
    </AuthFormWrapper>
  );
}

export default function RegisterPage() {
  return (
    <Suspense>
      <RegisterForm />
    </Suspense>
  );
}
