"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";

// ---------------------------------------------------------------------------
// Forgot password — Ory Kratos `recovery` browser self-service flow
// ---------------------------------------------------------------------------
// The recovery flow is multi-step but single-page: the user first submits
// their email, Kratos emails a code and returns the SAME flow re-rendered with
// a "code" input. Submitting a valid code creates a privileged session and
// Kratos redirects the browser to the `settings` flow to set a new password.
//
// We just keep rendering `flow.ui.nodes` — Kratos drives the step transitions.
// ---------------------------------------------------------------------------

function ForgotPasswordForm() {
  const { flow, loading, error, setFlow } = useKratosFlow("recovery");

  function handleResult(result: { status: number; ok: boolean; data: unknown }) {
    // A hard success (2xx with no body) means Kratos established a recovery
    // session and is redirecting the browser to the settings flow. With
    // `redirect: 'manual'` the redirect surfaces as ok=true / data=null —
    // navigate to settings so the user can pick a new password.
    if (result.ok && !result.data) {
      window.location.href = "/settings";
      return;
    }
    // Otherwise Kratos returned a flow body: either the same flow advanced to
    // the "code" step, or the same step re-rendered with validation messages.
    if (result.data && typeof result.data === "object" && "ui" in result.data) {
      setFlow(result.data as KratosFlow);
    }
  }

  return (
    <AuthFormWrapper
      title="Forgot password?"
      subtitle="Enter your email to receive a recovery code"
      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 && <KratosFlowForm flow={flow} onResult={handleResult} />}
      </div>
    </AuthFormWrapper>
  );
}

export default function ForgotPasswordPage() {
  return (
    <Suspense>
      <ForgotPasswordForm />
    </Suspense>
  );
}
