import { useDeltaAccount } from "@/hooks/use-delta-account";
import { Link } from "@tanstack/react-router";
import { Wallet, AlertCircle, RefreshCw } from "lucide-react";
import { useState } from "react";

export function WalletBadge() {
  const { creds, account, loading, refresh } = useDeltaAccount();
  const [spinning, setSpinning] = useState(false);

  const base =
    "hidden items-center gap-2 rounded-lg border px-3 py-1.5 text-xs transition sm:inline-flex focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";

  // Not linked yet
  if (!creds) {
    return (
      <Link
        to="/settings"
        aria-label="Wallet not linked, configure Delta credentials"
        title="Add your Delta Exchange API key in Settings to see your wallet."
        className={`${base} border-warning/40 bg-warning/5 text-warning hover:bg-warning/10`}
      >
        <Wallet className="h-3.5 w-3.5" aria-hidden />
        <span className="font-medium">Wallet not linked</span>
        <span className="hidden text-muted-foreground md:inline">· Configure</span>
      </Link>
    );
  }

  // Initial sync — skeleton
  if (loading && !account) {
    return (
      <div
        role="status"
        aria-live="polite"
        aria-label="Syncing Delta wallet balance"
        className={`${base} glass border-border/60`}
      >
        <span className="relative flex h-2 w-2" aria-hidden>
          <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-muted-foreground/50 opacity-70" />
          <span className="relative inline-flex h-2 w-2 rounded-full bg-muted-foreground/60" />
        </span>
        <Wallet className="h-3.5 w-3.5 text-muted-foreground" aria-hidden />
        <span className="hidden text-muted-foreground md:inline">Wallet</span>
        <span className="flex items-center gap-1.5" aria-hidden>
          <span className="h-3 w-16 animate-pulse rounded bg-muted-foreground/20" />
          <span className="h-3 w-8 animate-pulse rounded bg-muted-foreground/10" />
        </span>
        <span className="sr-only">Loading balance…</span>
      </div>
    );
  }

  // Error / auth failure — retry
  if (account && !account.connected) {
    const msg = account.hint ?? account.error ?? "Delta rejected your credentials";
    const onRetry = async (e: React.MouseEvent) => {
      e.preventDefault();
      setSpinning(true);
      try {
        await refresh();
      } finally {
        setSpinning(false);
      }
    };
    return (
      <div
        role="alert"
        className={`${base} border-bear/40 bg-bear/5 text-bear`}
        title={msg}
      >
        <AlertCircle className="h-3.5 w-3.5" aria-hidden />
        <span className="font-medium">Auth failed</span>
        <span className="hidden max-w-[10rem] truncate text-muted-foreground md:inline">
          · {account.error ?? "check keys"}
        </span>
        <button
          type="button"
          onClick={onRetry}
          aria-label="Retry Delta wallet connection"
          className="ml-1 inline-flex h-5 w-5 items-center justify-center rounded hover:bg-bear/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
        >
          <RefreshCw className={`h-3 w-3 ${spinning ? "animate-spin" : ""}`} aria-hidden />
        </button>
        <Link
          to="/settings"
          className="ml-0.5 underline underline-offset-2 hover:text-bear/80"
          aria-label="Open settings to fix Delta credentials"
        >
          Fix
        </Link>
      </div>
    );
  }

  const balance = account?.balance;
  const currency = account?.currency ?? "USDT";
  const formatted =
    typeof balance === "number"
      ? balance.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
      : "—";

  return (
    <Link
      to="/settings"
      aria-label={`Delta wallet balance ${formatted} ${currency}${loading ? ", refreshing" : ""}`}
      aria-live="polite"
      className={`${base} glass border-bull/30 hover:border-bull/60`}
      title={`Delta wallet · ${account?.email ?? account?.account_id ?? ""}`}
    >
      <span className="relative flex h-2 w-2" aria-hidden>
        <span className={`absolute inline-flex h-full w-full rounded-full bg-bull opacity-70 ${loading ? "animate-ping" : ""}`} />
        <span className="relative inline-flex h-2 w-2 rounded-full bg-bull" />
      </span>
      <Wallet className="h-3.5 w-3.5 text-bull" aria-hidden />
      <span className="hidden text-muted-foreground md:inline">Wallet</span>
      <span className="num font-semibold">
        {formatted} <span className="text-muted-foreground">{currency}</span>
      </span>
    </Link>
  );
}
