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

// ---------------------------------------------------------------------------
// Login — Ory Kratos `login` browser self-service flow
// ---------------------------------------------------------------------------

function LoginForm() {
  const { flow, loading, error, setFlow } = useKratosFlow("login");

  function handleResult(result: { status: number; ok: boolean; data: unknown }) {
    if (result.ok) {
      // Kratos completed the login (set the `ory_kratos_session` cookie).
      trackEvent(AnalyticsEvents.USER_SIGNED_IN, {
        method: "kratos",
        platform: "web",
      });
      window.location.href = "/app";
      return;
    }
    // 400 = validation errors; Kratos returns the same flow re-rendered with
    // messages. Re-render whatever Kratos returned.
    if (result.data && typeof result.data === "object" && "ui" in result.data) {
      setFlow(result.data as KratosFlow);
    }
  }

  return (
    <AuthFormWrapper
      title="Welcome back"
      subtitle="Sign in to your account"
      footer={
        <p>
          Don&apos;t have an account?{" "}
          <Link href="/register" className="text-primary hover:underline">
            Sign up
          </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="Sign in" />
            <div className="text-center">
              <Link
                href="/forgot-password"
                className="text-xs text-muted-foreground hover:text-primary"
              >
                Forgot password?
              </Link>
            </div>
          </>
        )}
      </div>
    </AuthFormWrapper>
  );
}

export default function LoginPage() {
  return (
    <Suspense>
      <LoginForm />
    </Suspense>
  );
}
