import { Link, useRouterState } from "@tanstack/react-router";
import { useState } from "react";
import {
  Search, Bell, MessageCircle, Menu, X, ChevronDown, Plus,
  Home, Server, Users, Trophy, Gavel, ShoppingBag, Palette, Newspaper, ScrollText, LifeBuoy, Moon,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel,
  DropdownMenuSeparator, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { GlobalSearch } from "@/components/navigation/GlobalSearch";
import { NotificationBell } from "@/components/navigation/NotificationPanel";
import { LiveUserBadge } from "@/components/common/LiveUserBadge";
import { useAuthStore } from "@/store/auth";
import { LariMark, WGCMark, formatGEL, formatWGC } from "@/lib/currency";
import { cn } from "@/lib/utils";

const NAV = [
  { to: "/", label: "Home", icon: Home },
  { to: "/servers", label: "Servers", icon: Server },
  { to: "/players", label: "Players", icon: Users },
  { to: "/rankings", label: "Rankings", icon: Trophy },
  { to: "/punishments", label: "Punishments", icon: Gavel },
  { to: "/store", label: "Store", icon: ShoppingBag },
  { to: "/skins", label: "Skins", icon: Palette },
  { to: "/subscription", label: "Subscription", icon: Moon },
  { to: "/news", label: "News", icon: Newspaper },
  { to: "/rules", label: "Rules", icon: ScrollText },
  { to: "/support", label: "Support", icon: LifeBuoy },
] as const;

export function Header() {
  const [mobileOpen, setMobileOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const pathname = useRouterState({ select: (s) => s.location.pathname });
  const { user, login, logout } = useAuthStore();

  return (
    <>
      <header className="sticky top-0 z-40 border-b border-border/60 bg-background/85 backdrop-blur-xl">
        <div className="mx-auto flex h-16 max-w-[1400px] items-center gap-4 px-4">
          <Link to="/" className="flex shrink-0 items-center gap-2">
            <div className="grid h-9 w-9 place-items-center rounded-lg gradient-primary shadow-glow">
              <span className="font-display text-lg font-bold text-primary-foreground">P</span>
            </div>
            <div className="hidden sm:block">
              <div className="font-display text-sm font-bold leading-none">PURPLE ZONE</div>
              <div className="text-[10px] uppercase tracking-widest text-muted-foreground">CS2 Community</div>
            </div>
          </Link>

          <nav className="ml-2 hidden items-center gap-0.5 lg:flex">
            {NAV.slice(0, 7).map((n) => {
              const active = pathname === n.to || (n.to !== "/" && pathname.startsWith(n.to));
              return (
                <Link
                  key={n.to}
                  to={n.to}
                  className={cn(
                    "relative px-3 py-2 text-sm font-medium transition-colors duration-200",
                    active ? "text-foreground" : "text-muted-foreground hover:text-foreground",
                  )}
                >
                  {n.label}
                  {active && (
                    <span className="absolute inset-x-2 -bottom-[17px] h-[2px] rounded-full gradient-primary" />
                  )}
                </Link>
              );
            })}
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <button className="flex items-center gap-1 px-3 py-2 text-sm font-medium text-muted-foreground transition-colors hover:text-foreground">
                  More <ChevronDown className="h-3.5 w-3.5" />
                </button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-48">
                {NAV.slice(7).map((n) => (
                  <DropdownMenuItem key={n.to} asChild>
                    <Link to={n.to} className="flex items-center gap-2">
                      <n.icon className="h-4 w-4" /> {n.label}
                    </Link>
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>
          </nav>

          <div className="ml-auto flex items-center gap-1.5">
            <button
              onClick={() => setSearchOpen(true)}
              className="hidden items-center gap-2 rounded-md border border-border bg-surface/60 px-3 py-1.5 text-sm text-muted-foreground transition-colors hover:border-primary/40 hover:text-foreground md:flex md:w-64 lg:w-72"
            >
              <Search className="h-4 w-4" />
              <span>Search players, servers…</span>
              <kbd className="ml-auto rounded border border-border bg-background px-1.5 py-0.5 text-[10px] font-mono">⌘K</kbd>
            </button>
            <Button size="icon" variant="ghost" className="md:hidden" onClick={() => setSearchOpen(true)}>
              <Search className="h-5 w-5" />
            </Button>
            <div className="hidden md:block"><LiveUserBadge compact /></div>

            {user && (
              <>
                <Button size="icon" variant="ghost" asChild className="hidden sm:inline-flex">
                  <Link to="/chat"><MessageCircle className="h-5 w-5" /></Link>
                </Button>
                <NotificationBell
                  trigger={
                    <Button size="icon" variant="ghost" className="relative">
                      <Bell className="h-5 w-5" />
                      <span className="absolute right-1.5 top-1.5 h-2 w-2 rounded-full bg-primary" />
                    </Button>
                  }
                />
                <div className="hidden items-stretch gap-1 sm:flex">
                  <div className="flex items-center gap-1 rounded-l-md border border-r-0 border-border bg-surface/60 pl-2.5 pr-2 py-1.5">
                    <LariMark className="h-3.5 w-3.5 text-secondary" />
                    <span className="font-mono text-sm font-semibold">{formatGEL(user.balance, { withSymbol: false })}</span>
                    <span className="text-[10px] uppercase tracking-wider text-muted-foreground">GEL</span>
                  </div>
                  <div className="flex items-center gap-1 border border-r-0 border-border bg-surface/60 pl-2 pr-2 py-1.5">
                    <WGCMark className="h-4 w-4" />
                    <span className="font-mono text-sm font-semibold">{user.coins.toLocaleString()}</span>
                    <span className="text-[10px] uppercase tracking-wider text-muted-foreground">WGC</span>
                  </div>
                  <Link
                    to="/account/balance"
                    aria-label="Top up balance"
                    title={`Top up (${formatGEL(user.balance)} · ${formatWGC(user.coins)})`}
                    className="grid place-items-center rounded-r-md border border-border bg-primary/15 px-2 text-secondary transition-colors hover:bg-primary/25"
                  >
                    <Plus className="h-4 w-4" />
                  </Link>
                </div>
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <button className="flex items-center gap-2 rounded-md border border-transparent p-1 transition-colors hover:border-border">
                      <Avatar className="h-8 w-8">
                        <AvatarImage src={user.avatar} />
                        <AvatarFallback>{user.name[0]}</AvatarFallback>
                      </Avatar>
                    </button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end" className="w-56">
                    <DropdownMenuLabel>
                      <div className="text-sm font-semibold">{user.name}</div>
                      <div className="text-xs text-muted-foreground">{user.steamId}</div>
                    </DropdownMenuLabel>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem asChild><Link to="/account">Overview</Link></DropdownMenuItem>
                    <DropdownMenuItem asChild><Link to="/account/profile">Profile</Link></DropdownMenuItem>
                    <DropdownMenuItem asChild><Link to="/account/balance">Balance & wallet</Link></DropdownMenuItem>
                    <DropdownMenuItem asChild><Link to="/account/orders">Orders</Link></DropdownMenuItem>
                    <DropdownMenuItem asChild><Link to="/account/skins">Skin loadouts</Link></DropdownMenuItem>
                    <DropdownMenuItem asChild><Link to="/account/settings">Settings</Link></DropdownMenuItem>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem asChild><Link to="/admin">Admin panel</Link></DropdownMenuItem>
                    <DropdownMenuItem onClick={logout}>Sign out</DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </>
            )}
            {!user && (
              <Button onClick={login} className="gradient-primary text-primary-foreground shadow-glow hover:opacity-95">
                <svg viewBox="0 0 24 24" className="mr-1.5 h-4 w-4 fill-current"><path d="M12 0C5.373 0 0 5.373 0 12c0 5.302 3.438 9.8 8.208 11.387l4.06-1.887a4.5 4.5 0 0 0 8.735-1.9L24 15.09V12C24 5.373 18.627 0 12 0zm5.55 15.09a3 3 0 1 1-2.994-3l-2.322 1.08a4.51 4.51 0 0 1-4.234 4.5L4.29 19.5A10.53 10.53 0 0 1 1.5 12a10.5 10.5 0 1 1 16.05 3.09z"/></svg>
                Sign in with Steam
              </Button>
            )}
            <Button size="icon" variant="ghost" className="lg:hidden" onClick={() => setMobileOpen(true)}>
              <Menu className="h-5 w-5" />
            </Button>
          </div>
        </div>
      </header>

      {/* Mobile drawer */}
      {mobileOpen && (
        <div className="fixed inset-0 z-50 lg:hidden">
          <div className="absolute inset-0 bg-background/80 backdrop-blur-sm" onClick={() => setMobileOpen(false)} />
          <div className="absolute right-0 top-0 h-full w-80 border-l border-border bg-surface p-4">
            <div className="mb-6 flex items-center justify-between">
              <span className="font-display font-bold">Menu</span>
              <Button size="icon" variant="ghost" onClick={() => setMobileOpen(false)}><X className="h-5 w-5" /></Button>
            </div>
            <nav className="flex flex-col gap-1">
              {NAV.map((n) => (
                <Link
                  key={n.to}
                  to={n.to}
                  onClick={() => setMobileOpen(false)}
                  className="flex items-center gap-3 rounded-md px-3 py-2.5 text-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
                >
                  <n.icon className="h-4 w-4" /> {n.label}
                </Link>
              ))}
            </nav>
            <div className="mt-4 border-t border-border pt-4"><LiveUserBadge /></div>
          </div>
        </div>
      )}

      <GlobalSearch open={searchOpen} onOpenChange={setSearchOpen} />
    </>
  );
}
