"use client";

import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { callAuthEndpoint } from "athena-auth-js";
import {
  AthenaAuthAccountSettingsDialog,
  type AthenaAuthAccountEmailAddress,
  type AthenaAuthConnectedAccount,
  type AthenaAuthAccountSettingsRenderMode,
  type AthenaAuthSecurityEntry,
} from "athena-auth-ui-js";

import { authClient } from "../lib/auth-client";
import { SharedBackButton } from "./shared-back-button";
import { Badge } from "./ui/badge";

function capitalize(value: string): string {
  if (value.length === 0) return value;
  return value.slice(0, 1).toUpperCase() + value.slice(1);
}

function prettifyProvider(provider: string): string {
  const normalized = provider.trim().toLowerCase();
  if (normalized === "github") return "GitHub";
  if (normalized === "google") return "Google";
  if (normalized === "discord") return "Discord";
  if (normalized === "cloudflare") return "Cloudflare";
  if (normalized === "email-password") return "Email password";
  if (normalized === "email_otp") return "Email OTP";
  return normalized
    .split(/[-_]/g)
    .filter((part) => part.length > 0)
    .map((part) => capitalize(part))
    .join(" ");
}

function firstString(
  record: Record<string, unknown>,
  keys: string[],
): string | null {
  for (const key of keys) {
    const value = record[key];
    if (typeof value === "string" && value.length > 0) {
      return value;
    }
  }
  return null;
}

function normalizeConnectedAccount(
  input: unknown,
): AthenaAuthConnectedAccount | null {
  if (!input || typeof input !== "object") return null;
  const record = input as Record<string, unknown>;
  const id = firstString(record, ["id", "accountId", "account_id"]);
  const provider = firstString(record, ["providerId", "provider_id", "provider"]);

  if (!id || !provider) {
    return null;
  }

  const handle = firstString(record, [
    "username",
    "login",
    "accountId",
    "account_id",
    "email",
  ]);

  return {
    id,
    providerLabel: prettifyProvider(provider),
    handle,
  };
}

export function AccountSettingsView() {
  const router = useRouter();
  const { data, isPending, error } = authClient.useSession();
  const [renderMode, setRenderMode] =
    useState<AthenaAuthAccountSettingsRenderMode>("dialog");
  const [dialogOpen, setDialogOpen] = useState(false);
  const [accounts, setAccounts] = useState<AthenaAuthConnectedAccount[]>([]);
  const [accountsLoading, setAccountsLoading] = useState(true);
  const [accountsError, setAccountsError] = useState<string | null>(null);
  const [notice, setNotice] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;

    const loadAccounts = async () => {
      setAccountsLoading(true);
      setAccountsError(null);

      const result = await callAuthEndpoint<unknown[]>("/list-accounts", {
        method: "GET",
      });

      if (cancelled) return;

      if (!result.ok) {
        setAccountsError(
          result.message || "Failed to load connected accounts.",
        );
        setAccounts([]);
        setAccountsLoading(false);
        return;
      }

      const normalized = (Array.isArray(result.body) ? result.body : [])
        .map(normalizeConnectedAccount)
        .filter((entry): entry is AthenaAuthConnectedAccount => entry !== null);

      setAccounts(normalized);
      setAccountsLoading(false);
    };

    void loadAccounts();

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

  useEffect(() => {
    if (renderMode === "inline" && dialogOpen) {
      setDialogOpen(false);
    }
  }, [dialogOpen, renderMode]);

  const userRecord = (data?.user ?? {}) as unknown as Record<string, unknown>;
  const name = firstString(userRecord, ["name", "username", "email"]) ?? "User";
  const avatarUrl = firstString(userRecord, ["image", "avatarUrl", "avatar_url"]);
  const primaryEmail = firstString(userRecord, ["email"]);

  const emails: AthenaAuthAccountEmailAddress[] = useMemo(() => {
    if (!primaryEmail) return [];
    return [{ id: "primary", address: primaryEmail, isPrimary: true }];
  }, [primaryEmail]);

  const securityEntries = useMemo<AthenaAuthSecurityEntry[]>(
    () => [
      {
        id: "password",
        title: "Password",
        description: "Reset your account password using the built-in flow.",
        actionLabel: "Open password reset",
        onAction: () => {
          router.push("/forgot-password");
        },
      },
      {
        id: "passkeys",
        title: "Passkeys and two-factor",
        description:
          "Register passkeys or test challenge flows in the auth surface.",
        actionLabel: "Open auth surface",
        onAction: () => {
          router.push("/login");
        },
      },
      {
        id: "sessions",
        title: "Session activity",
        description: "Review and revoke active sessions on every device.",
        actionLabel: "Open session activity",
        onAction: () => {
          router.push("/session/activity");
        },
      },
    ],
    [router],
  );

  const topStatusVariant =
    isPending || accountsLoading
      ? "secondary"
      : error || accountsError
        ? "destructive"
        : "success";
  const topStatusText =
    isPending || accountsLoading
      ? "loading"
      : error || accountsError
        ? "error"
        : "ready";

  return (
    <main className="mx-auto w-full max-w-6xl px-4 pb-10 pt-8">
      <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
        <SharedBackButton fallbackHref="/session" />
        <div className="flex flex-wrap items-center gap-2 text-xs">
          <Badge variant={topStatusVariant}>settings: {topStatusText}</Badge>
          <Badge variant="secondary">mode: {renderMode}</Badge>
          {renderMode === "dialog" ? (
            <Badge variant="secondary">
              dialog: {dialogOpen ? "open" : "closed"}
            </Badge>
          ) : null}
          <Badge variant="secondary">emails: {emails.length}</Badge>
          <Badge variant="secondary">connected accounts: {accounts.length}</Badge>
        </div>
      </div>

      {error ? (
        <p className="mb-3 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
          Session error: {error.message}
        </p>
      ) : null}
      {accountsError ? (
        <p className="mb-3 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
          Accounts error: {accountsError}
        </p>
      ) : null}
      {notice ? (
        <p className="mb-3 rounded-md border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-700">
          {notice}
        </p>
      ) : null}

      <section className="mb-4 rounded-xl border border-slate-200 bg-white/90 p-3">
        <div className="flex flex-wrap items-center gap-3">
          <label
            htmlFor="settings-render-mode"
            className="text-sm font-medium text-slate-700"
          >
            Settings surface mode
          </label>
          <select
            id="settings-render-mode"
            value={renderMode}
            onChange={(event) => {
              setRenderMode(
                event.target.value as AthenaAuthAccountSettingsRenderMode,
              );
            }}
            className="rounded-lg border border-slate-300 bg-white px-3 py-1.5 text-sm text-slate-900"
          >
            <option value="dialog">Dialog</option>
            <option value="inline">Integrated page</option>
          </select>
          <span className="text-xs text-slate-500">
            Dialog mode opens from a trigger button; integrated mode renders
            directly in-page.
          </span>
        </div>
      </section>

      <AthenaAuthAccountSettingsDialog
        accountTitle="Account"
        accountDescription="Manage your account info."
        renderMode={renderMode}
        open={dialogOpen}
        onOpenChange={setDialogOpen}
        triggerLabel="Open settings dialog"
        closeLabel="Close settings dialog"
        profile={{ name, avatarUrl }}
        emails={emails}
        connectedAccounts={accounts}
        securityEntries={securityEntries}
        onUpdateProfile={() => {
          setNotice("Profile updates are available through the auth submit form.");
          router.push("/login");
        }}
        onAddEmail={() => {
          setNotice("Use endpoint lab to run change-email scenarios.");
          router.push("/endpoint-lab");
        }}
        onConnectAccount={() => {
          setNotice("Use social sign-in on the auth surface to connect providers.");
          router.push("/login");
        }}
      />
    </main>
  );
}
