import { Link, useRouterState } from "@tanstack/react-router";
import {
  ArrowLeftRight,
  Home,
  Layers,
  PlusCircle,
  Store,
  User,
} from "lucide-react";
import { useEffect, useState } from "react";
import { CreatedWithGrokBanner } from "@/components/created-with-grok-banner";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { useCurrentUserState } from "@/lib/auth/use-current-user";
import { getMyProfile, getPendingTradeCount } from "@/lib/server/api";
import type { Profile } from "@/lib/types";
import { cn } from "@/lib/utils";

const nav = [
  { to: "/", label: "Feed", icon: Home },
  { to: "/marketplace", label: "Market", icon: Store },
  { to: "/create", label: "Create", icon: PlusCircle },
  { to: "/collection", label: "Cards", icon: Layers },
  { to: "/trades", label: "Trades", icon: ArrowLeftRight },
] as const;

export function AppShell({ children }: { children: React.ReactNode }) {
  const { user, isPending } = useCurrentUserState();
  const pathname = useRouterState({ select: (s) => s.location.pathname });
  const [profile, setProfile] = useState<Profile | null>(null);
  const [pendingTrades, setPendingTrades] = useState(0);

  useEffect(() => {
    if (!user) {
      setProfile(null);
      setPendingTrades(0);
      return;
    }
    let cancelled = false;
    void (async () => {
      try {
        const [p, count] = await Promise.all([getMyProfile(), getPendingTradeCount()]);
        if (!cancelled) {
          setProfile(p);
          setPendingTrades(count);
        }
      } catch {
        if (!cancelled) {
          setProfile(null);
          setPendingTrades(0);
        }
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [user?.id]);

  return (
    <div className="min-h-dvh bg-bg text-fg flex flex-col">
      <CreatedWithGrokBanner />
      <header className="sticky top-0 z-40 border-b border-border/80 bg-bg/90 backdrop-blur-md">
        <div className="mx-auto flex h-14 max-w-5xl items-center justify-between gap-3 px-4">
          <Link to="/" className="flex items-center gap-2 min-w-0">
            <span className="grid h-8 w-8 place-items-center rounded-[var(--radius-sm)] bg-accent text-accent-fg font-display text-lg leading-none">
              D
            </span>
            <span className="font-display text-2xl tracking-wide text-fg leading-none">
              DUGOUT
            </span>
          </Link>

          <nav className="hidden md:flex items-center gap-1">
            {nav.map((item) => {
              const active =
                item.to === "/"
                  ? pathname === "/"
                  : pathname.startsWith(item.to);
              const Icon = item.icon;
              return (
                <Link
                  key={item.to}
                  to={item.to}
                  className={cn(
                    "relative inline-flex h-10 items-center gap-2 rounded-[var(--radius-md)] px-3 text-sm font-medium transition-colors",
                    active
                      ? "bg-surface-2 text-fg"
                      : "text-muted hover:text-fg hover:bg-surface-2/60",
                  )}
                >
                  <Icon className="h-4 w-4" />
                  {item.label}
                  {item.to === "/trades" && pendingTrades > 0 && (
                    <span className="absolute -right-0.5 -top-0.5 grid h-4 min-w-4 place-items-center rounded-full bg-accent px-1 text-[10px] font-semibold text-accent-fg">
                      {pendingTrades}
                    </span>
                  )}
                </Link>
              );
            })}
          </nav>

          <div className="flex items-center gap-2">
            {isPending ? (
              <div className="h-9 w-9 animate-pulse rounded-full bg-surface-2" />
            ) : user ? (
              <Link
                to={profile ? "/u/$handle" : "/collection"}
                params={profile ? { handle: profile.handle } : undefined}
                className="flex items-center gap-2 rounded-full border border-border bg-surface-2/60 py-1 pl-1 pr-3 hover:border-border-strong transition-colors"
              >
                <Avatar className="h-7 w-7">
                  {profile?.avatarUrl || user.profileImageUrl ? (
                    <AvatarImage src={profile?.avatarUrl || user.profileImageUrl || undefined} />
                  ) : null}
                  <AvatarFallback>
                    {(profile?.displayName || user.displayName || "P").charAt(0)}
                  </AvatarFallback>
                </Avatar>
                <span className="hidden sm:inline text-sm font-medium truncate max-w-[100px]">
                  {profile ? `@${profile.handle}` : "Profile"}
                </span>
              </Link>
            ) : (
              <Button asChild size="sm">
                <Link to="/login">Sign in</Link>
              </Button>
            )}
          </div>
        </div>
      </header>

      <main className="flex-1 mx-auto w-full max-w-5xl px-4 py-5 pb-24 md:pb-8">{children}</main>

      {/* Mobile bottom nav */}
      <nav className="md:hidden fixed bottom-0 inset-x-0 z-40 border-t border-border bg-bg/95 backdrop-blur-md safe-pb">
        <div className="mx-auto flex max-w-lg items-stretch justify-around px-1 pt-1">
          {nav.map((item) => {
            const active =
              item.to === "/" ? pathname === "/" : pathname.startsWith(item.to);
            const Icon = item.icon;
            return (
              <Link
                key={item.to}
                to={item.to}
                className={cn(
                  "relative flex min-h-12 min-w-[56px] flex-col items-center justify-center gap-0.5 rounded-[var(--radius-sm)] px-2 text-[10px] font-medium transition-colors",
                  active ? "text-fg" : "text-muted",
                )}
              >
                <Icon className={cn("h-5 w-5", active && "text-accent")} />
                {item.label}
                {item.to === "/trades" && pendingTrades > 0 && (
                  <span className="absolute right-2 top-1 grid h-4 min-w-4 place-items-center rounded-full bg-accent px-1 text-[9px] font-semibold text-accent-fg">
                    {pendingTrades}
                  </span>
                )}
              </Link>
            );
          })}
          {user && profile && (
            <Link
              to="/u/$handle"
              params={{ handle: profile.handle }}
              className={cn(
                "flex min-h-12 min-w-[56px] flex-col items-center justify-center gap-0.5 text-[10px] font-medium",
                pathname.startsWith("/u/") ? "text-fg" : "text-muted",
              )}
            >
              <User className="h-5 w-5" />
              Me
            </Link>
          )}
        </div>
      </nav>
    </div>
  );
}
