import { Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { ThemeToggle } from "./ThemeToggle";
import { NotificationsBell } from "./NotificationsBell";
import { getWalletAndProfile } from "@/lib/wallet.functions";

export function AppHeader() {
  const fetchWallet = useServerFn(getWalletAndProfile);
  const { data: wp } = useQuery({
    queryKey: ["wallet"],
    queryFn: () => fetchWallet(),
    staleTime: 30_000,
  });

  const profile = wp?.profile as { full_name?: string | null; email?: string | null; avatar_url?: string | null } | undefined;
  const displayName =
    (profile?.full_name?.trim().split(" ")[0]) ||
    (profile?.email?.split("@")[0]) ||
    "there";

  const initials =
    (profile?.full_name ?? profile?.email ?? "U")
      .split(" ")
      .map((s: string) => s[0])
      .join("")
      .slice(0, 2)
      .toUpperCase();

  return (
    <header className="sticky top-0 z-40 border-b border-border/60 bg-background/70 backdrop-blur-xl supports-[backdrop-filter]:bg-background/60">
      <div className="flex items-center justify-between gap-2 px-3 py-2.5">
        <Link to="/app/profile" className="flex min-w-0 items-center gap-2" aria-label="Your profile">
          {profile?.avatar_url ? (
            <img
              src={profile.avatar_url}
              alt=""
              className="h-8 w-8 shrink-0 rounded-full object-cover ring-2 ring-primary/30"
            />
          ) : (
            <span className="grid h-8 w-8 shrink-0 place-items-center rounded-full bg-gradient-primary text-[11px] font-bold text-primary-foreground">
              {initials}
            </span>
          )}
          <span className="truncate text-sm font-bold tracking-tight text-foreground">
            Hi, {displayName}
          </span>
        </Link>

        <div className="flex shrink-0 items-center gap-0.5">
          <NotificationsBell />
          <ThemeToggle />
        </div>
      </div>
    </header>
  );
}
