import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { 
  DropdownMenu, 
  DropdownMenuContent, 
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuLabel,
  DropdownMenuTrigger 
} from "@/components/ui/dropdown-menu";
import { useAuth } from "@/hooks/useAuth";
import { SportBadge } from "@/components/sport/sport-badge";
import { OnboardingMenu } from "@/components/onboarding/onboarding-menu";
import { Trophy, Bell, LogOut, User, Settings, CreditCard, Moon, Sun, Shield } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { Link } from "wouter";
import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";

interface Notification {
  id: number;
  isRead: boolean;
}

export default function Header() {
  const { user, logout } = useAuth();
  const { toast } = useToast();
  const [darkMode, setDarkMode] = useState(false);

  const { data: unreadNotifications = [] } = useQuery<Notification[]>({
    queryKey: ["/api/notifications/unread"],
    enabled: !!user,
  });

  const unreadCount = unreadNotifications.length;

  useEffect(() => {
    const isDark = document.documentElement.classList.contains('dark');
    setDarkMode(isDark);
  }, []);

  const toggleDarkMode = () => {
    const newMode = !darkMode;
    setDarkMode(newMode);
    if (newMode) {
      document.documentElement.classList.add('dark');
      localStorage.setItem('theme', 'dark');
    } else {
      document.documentElement.classList.remove('dark');
      localStorage.setItem('theme', 'light');
    }
  };

  const handleLogout = async () => {
    try {
      await logout();
      toast({
        title: "Logged out",
        description: "You have been successfully logged out",
      });
    } catch (error) {
      console.error("Logout error:", error);
      toast({
        title: "Error",
        description: "Failed to logout. Please try again.",
        variant: "destructive",
      });
    }
  };

  const getRoleBadge = () => {
    const role = (user as any)?.role;
    if (role === 'superadmin') return { label: 'Super Admin', variant: 'destructive' as const, color: 'bg-gradient-to-r from-red-500 to-pink-600' };
    if (role === 'admin') return { label: 'Administrator', variant: 'default' as const, color: 'bg-gradient-to-r from-blue-500 to-purple-600' };
    return { label: 'User', variant: 'secondary' as const, color: 'bg-slate-500' };
  };

  const roleBadge = getRoleBadge();

  return (
    <header className="fixed top-0 left-0 right-0 z-30 bg-white dark:bg-slate-900 border-b border-slate-200 dark:border-slate-800 shadow-sm backdrop-blur-md bg-white/80 dark:bg-slate-900/80">
      <div className="px-6 py-3.5">
        <div className="flex items-center justify-between">
          {/* Logo Section */}
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-3">
              <div className="relative group">
                <div className="absolute inset-0 bg-gradient-to-br from-blue-500 to-purple-600 rounded-xl blur-md opacity-50 group-hover:opacity-75 transition-opacity"></div>
                <div className="relative w-11 h-11 bg-gradient-to-br from-blue-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg">
                  <Trophy className="text-white w-6 h-6" />
                </div>
              </div>
              <div className="hidden md:block">
                <h1 className="text-lg font-bold text-slate-900 dark:text-white tracking-tight">
                  SportsPro
                </h1>
                <p className="text-[10px] font-medium text-slate-500 dark:text-slate-400 tracking-wide">
                  Sports Management Platform
                </p>
              </div>
            </div>
          </div>

          {/* Header Actions */}
          <div className="flex items-center gap-2">
            {/* Sport Badge */}
            <div className="hidden lg:flex">
              <SportBadge />
            </div>
            
            {/* Dark Mode Toggle */}
            <Button 
              variant="ghost" 
              size="icon"
              onClick={toggleDarkMode}
              className="h-10 w-10 rounded-xl hover:bg-slate-100 dark:hover:bg-slate-800 transition-all hover:scale-105"
              data-testid="button-dark-mode"
              aria-label={darkMode ? "Switch to light mode" : "Switch to dark mode"}
            >
              {darkMode ? (
                <Sun className="h-5 w-5 text-amber-500" />
              ) : (
                <Moon className="h-5 w-5 text-slate-600 dark:text-slate-400" />
              )}
            </Button>
            
            {/* Onboarding Menu */}
            <div className="hidden md:flex">
              <OnboardingMenu />
            </div>
            
            {/* Notifications */}
            <Link to="/notifications">
              <Button 
                variant="ghost" 
                size="icon"
                className="relative h-10 w-10 rounded-xl hover:bg-slate-100 dark:hover:bg-slate-800 transition-all hover:scale-105 group"
                data-testid="button-notifications"
                aria-label={unreadCount > 0 ? `Notifications (${unreadCount} unread)` : "Notifications"}
              >
                <Bell className="h-5 w-5 text-slate-600 dark:text-slate-400 group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors" />
                {unreadCount > 0 && (
                  <Badge className="absolute -top-1 -right-1 h-5 min-w-5 flex items-center justify-center p-0 px-1.5 text-[10px] font-bold bg-gradient-to-br from-red-500 to-red-600 text-white border-2 border-white dark:border-slate-900 shadow-lg animate-pulse">
                    {unreadCount > 99 ? '99+' : unreadCount}
                  </Badge>
                )}
              </Button>
            </Link>
            
            {/* User Profile Dropdown */}
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button 
                  variant="ghost" 
                  className="relative h-10 px-3 gap-2.5 rounded-xl hover:bg-slate-100 dark:hover:bg-slate-800 transition-all hover:scale-105 group" 
                  data-testid="button-profile"
                  aria-label="User menu"
                >
                  <Avatar className="h-8 w-8 ring-2 ring-blue-500/30 dark:ring-purple-500/30 ring-offset-2 ring-offset-background transition-all group-hover:ring-blue-500/50 dark:group-hover:ring-purple-500/50">
                    <AvatarImage 
                      src={(user as any)?.profileImageUrl || undefined} 
                      alt={(user as any)?.firstName || "User"} 
                    />
                    <AvatarFallback className="bg-gradient-to-br from-blue-500 to-purple-600 text-white font-bold text-xs">
                      {((user as any)?.firstName?.[0] || '') + ((user as any)?.lastName?.[0] || '')}
                    </AvatarFallback>
                  </Avatar>
                  <div className="hidden xl:flex flex-col items-start">
                    <span className="text-sm font-semibold text-slate-900 dark:text-white leading-none">
                      {(user as any)?.firstName}
                    </span>
                    <span className="text-xs text-slate-500 dark:text-slate-400 leading-none mt-1">
                      {roleBadge.label}
                    </span>
                  </div>
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent className="w-72 shadow-xl border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900" align="end" forceMount>
                <DropdownMenuLabel className="p-4">
                  <div className="flex items-start gap-3">
                    <Avatar className="h-12 w-12 ring-2 ring-blue-500/30 dark:ring-purple-500/30">
                      <AvatarImage 
                        src={(user as any)?.profileImageUrl || undefined} 
                        alt={(user as any)?.firstName || "User"} 
                      />
                      <AvatarFallback className="bg-gradient-to-br from-blue-500 to-purple-600 text-white font-bold">
                        {((user as any)?.firstName?.[0] || '') + ((user as any)?.lastName?.[0] || '')}
                      </AvatarFallback>
                    </Avatar>
                    <div className="flex-1 min-w-0">
                      <p className="font-bold text-base text-slate-900 dark:text-white truncate">
                        {(user as any)?.firstName} {(user as any)?.lastName}
                      </p>
                      <p className="text-sm text-slate-600 dark:text-slate-400 truncate">
                        {(user as any)?.email}
                      </p>
                      <div className="mt-2 flex items-center gap-1.5">
                        <Shield className="h-3 w-3 text-slate-500" />
                        <span className="text-xs font-semibold text-slate-700 dark:text-slate-300">
                          {roleBadge.label}
                        </span>
                      </div>
                    </div>
                  </div>
                </DropdownMenuLabel>
                <DropdownMenuSeparator className="bg-slate-200 dark:bg-slate-800" />
                <div className="p-1.5">
                  <Link to="/profile">
                    <DropdownMenuItem className="cursor-pointer rounded-lg py-2.5 hover:bg-blue-50 dark:hover:bg-blue-950/30 group" data-testid="dropdown-profile">
                      <div className="flex items-center gap-3 w-full">
                        <div className="w-8 h-8 rounded-lg bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center group-hover:bg-blue-200 dark:group-hover:bg-blue-900/50 transition-colors">
                          <User className="h-4 w-4 text-blue-600 dark:text-blue-400" />
                        </div>
                        <span className="font-medium text-slate-900 dark:text-white">My Profile</span>
                      </div>
                    </DropdownMenuItem>
                  </Link>
                  <Link to="/settings">
                    <DropdownMenuItem className="cursor-pointer rounded-lg py-2.5 hover:bg-purple-50 dark:hover:bg-purple-950/30 group" data-testid="dropdown-settings">
                      <div className="flex items-center gap-3 w-full">
                        <div className="w-8 h-8 rounded-lg bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center group-hover:bg-purple-200 dark:group-hover:bg-purple-900/50 transition-colors">
                          <Settings className="h-4 w-4 text-purple-600 dark:text-purple-400" />
                        </div>
                        <span className="font-medium text-slate-900 dark:text-white">Settings</span>
                      </div>
                    </DropdownMenuItem>
                  </Link>
                  <Link to="/subscriptions">
                    <DropdownMenuItem className="cursor-pointer rounded-lg py-2.5 hover:bg-green-50 dark:hover:bg-green-950/30 group" data-testid="dropdown-subscription">
                      <div className="flex items-center gap-3 w-full">
                        <div className="w-8 h-8 rounded-lg bg-green-100 dark:bg-green-900/30 flex items-center justify-center group-hover:bg-green-200 dark:group-hover:bg-green-900/50 transition-colors">
                          <CreditCard className="h-4 w-4 text-green-600 dark:text-green-400" />
                        </div>
                        <span className="font-medium text-slate-900 dark:text-white">Subscription</span>
                      </div>
                    </DropdownMenuItem>
                  </Link>
                </div>
                <DropdownMenuSeparator className="bg-slate-200 dark:bg-slate-800" />
                <div className="p-1.5">
                  <DropdownMenuItem 
                    onClick={handleLogout} 
                    className="cursor-pointer rounded-lg py-2.5 hover:bg-red-50 dark:hover:bg-red-950/30 group" 
                    data-testid="dropdown-logout"
                  >
                    <div className="flex items-center gap-3 w-full">
                      <div className="w-8 h-8 rounded-lg bg-red-100 dark:bg-red-900/30 flex items-center justify-center group-hover:bg-red-200 dark:group-hover:bg-red-900/50 transition-colors">
                        <LogOut className="h-4 w-4 text-red-600 dark:text-red-400" />
                      </div>
                      <span className="font-medium text-red-600 dark:text-red-400">Log out</span>
                    </div>
                  </DropdownMenuItem>
                </div>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
      </div>
    </header>
  );
}
