"use client";

// ---------------------------------------------------------------------------
// ChangePasswordForm — password changes are owned by Ory Kratos
// ---------------------------------------------------------------------------
// The honeyDue Go API no longer handles passwords. Changing a password is a
// Kratos `settings` browser self-service flow. This card renders the password
// group of that flow inline so the user never leaves the settings page.
// ---------------------------------------------------------------------------

import { useEffect, useState } from "react";
import { Loader2 } from "lucide-react";

import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { KratosFlowForm } from "@/components/auth/kratos-flow-form";
import { KratosMessages } from "@/components/auth/kratos-messages";
import {
  browserFlowUrl,
  getFlow,
  type KratosFlow,
  type KratosUiNode,
} from "@/lib/kratos";

export function ChangePasswordForm() {
  const [flow, setFlow] = useState<KratosFlow | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Initialize a Kratos settings flow on mount. We fetch it directly (the user
  // is already logged in, so the settings flow can be created via the browser
  // endpoint, which responds with the flow JSON for a live session).
  useEffect(() => {
    let cancelled = false;

    // State is only mutated from the async callbacks — the initial
    // `loading: true` covers the in-flight window.
    fetch(browserFlowUrl("settings"), {
      credentials: "include",
      headers: { Accept: "application/json" },
      redirect: "follow",
    })
      .then(async (res) => {
        if (cancelled) return;
        if (res.ok) {
          const data = (await res.json()) as KratosFlow;
          setFlow(data);
          setError(null);
        } else {
          setError("Could not load the password form.");
        }
      })
      .catch(() => {
        if (!cancelled) setError("Could not load the password form.");
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });

    return () => {
      cancelled = true;
    };
  }, []);

  function handleResult(result: { status: number; ok: boolean; data: unknown }) {
    if (result.data && typeof result.data === "object" && "ui" in result.data) {
      setFlow(result.data as KratosFlow);
    } else if (result.ok && flow) {
      // Re-fetch the flow so the form (and any success message) is fresh.
      getFlow("settings", flow.id)
        .then(setFlow)
        .catch(() => {});
    }
  }

  // Render only the password-related nodes of the settings flow.
  const passwordFlow: KratosFlow | null = flow
    ? {
        ...flow,
        ui: {
          ...flow.ui,
          nodes: flow.ui.nodes.filter(
            (n: KratosUiNode) => n.group === "password" || n.group === "default",
          ),
        },
      }
    : null;

  return (
    <Card>
      <CardHeader>
        <CardTitle>Change Password</CardTitle>
        <CardDescription>
          Update your password to keep your account secure.
        </CardDescription>
      </CardHeader>
      <CardContent>
        <div className="flex flex-col gap-4">
          <KratosMessages flow={flow} error={error} />

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

          {passwordFlow && (
            <KratosFlowForm
              flow={passwordFlow}
              onResult={handleResult}
              submitLabel="Update Password"
            />
          )}
        </div>
      </CardContent>
    </Card>
  );
}
