import { useState, useRef, useEffect, useCallback } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Cloud, User, Settings, Key, LogOut, ChevronDown, Command } from 'lucide-react';
import { ThemeToggle } from '@/components/ui/theme-toggle';
import { Button } from '@/components/ui/button';
import { useAuth } from '@/contexts/AuthContext';

export function Header() {
  const { user, isAuthenticated, logout } = useAuth();
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const navigate = useNavigate();

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsDropdownOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const handleLogout = useCallback(() => {
    logout();
    navigate('/login');
  }, [logout, navigate]);

  const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
    if (e.key === 'Escape') {
      setIsDropdownOpen(false);
    }
  }, []);

  return (
    <header className="border-b bg-card sticky top-0 z-50" role="banner">
      <div className="flex h-16 items-center px-6">
        <Link 
          to="/" 
          className="flex items-center gap-2 font-bold text-xl"
          aria-label="mockupAWS Home"
        >
          <Cloud className="h-6 w-6" aria-hidden="true" />
          <span>mockupAWS</span>
        </Link>
        
        {/* Keyboard shortcut hint */}
        <div className="hidden md:flex items-center ml-4 text-xs text-muted-foreground">
          <kbd className="px-1.5 py-0.5 bg-muted rounded mr-1">
            {navigator.platform.includes('Mac') ? '⌘' : 'Ctrl'}
          </kbd>
          <kbd className="px-1.5 py-0.5 bg-muted rounded">K</kbd>
          <span className="ml-2">for commands</span>
        </div>

        <div className="ml-auto flex items-center gap-4">
          <span className="text-sm text-muted-foreground hidden sm:inline">
            AWS Cost Simulator
          </span>
          <div data-tour="theme-toggle">
            <ThemeToggle />
          </div>
          
          {isAuthenticated && user ? (
            <div className="relative" ref={dropdownRef}>
              <Button
                variant="ghost"
                className="flex items-center gap-2"
                onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                aria-expanded={isDropdownOpen}
                aria-haspopup="true"
                aria-label="User menu"
              >
                <User className="h-4 w-4" aria-hidden="true" />
                <span className="hidden sm:inline">{user.full_name || user.email}</span>
                <ChevronDown className="h-4 w-4" aria-hidden="true" />
              </Button>

              {isDropdownOpen && (
                <div 
                  className="absolute right-0 mt-2 w-56 rounded-md border bg-popover shadow-lg"
                  role="menu"
                  aria-orientation="vertical"
                  onKeyDown={handleKeyDown}
                >
                  <div className="p-2">
                    <div className="px-2 py-1.5 text-sm font-medium">
                      {user.full_name}
                    </div>
                    <div className="px-2 py-0.5 text-xs text-muted-foreground">
                      {user.email}
                    </div>
                  </div>
                  <div className="border-t my-1" role="separator" />
                  <div className="p-1">
                    <button
                      onClick={() => {
                        setIsDropdownOpen(false);
                        navigate('/profile');
                      }}
                      className="w-full flex items-center gap-2 px-2 py-1.5 text-sm rounded-sm hover:bg-accent hover:text-accent-foreground transition-colors"
                      role="menuitem"
                    >
                      <User className="h-4 w-4" aria-hidden="true" />
                      Profile
                    </button>
                    <button
                      onClick={() => {
                        setIsDropdownOpen(false);
                        navigate('/settings');
                      }}
                      className="w-full flex items-center gap-2 px-2 py-1.5 text-sm rounded-sm hover:bg-accent hover:text-accent-foreground transition-colors"
                      role="menuitem"
                    >
                      <Settings className="h-4 w-4" aria-hidden="true" />
                      Settings
                    </button>
                    <button
                      onClick={() => {
                        setIsDropdownOpen(false);
                        navigate('/settings/api-keys');
                      }}
                      className="w-full flex items-center gap-2 px-2 py-1.5 text-sm rounded-sm hover:bg-accent hover:text-accent-foreground transition-colors"
                      role="menuitem"
                    >
                      <Key className="h-4 w-4" aria-hidden="true" />
                      API Keys
                    </button>
                    <button
                      onClick={() => {
                        setIsDropdownOpen(false);
                        navigate('/analytics');
                      }}
                      className="w-full flex items-center gap-2 px-2 py-1.5 text-sm rounded-sm hover:bg-accent hover:text-accent-foreground transition-colors"
                      role="menuitem"
                    >
                      <Command className="h-4 w-4" aria-hidden="true" />
                      Analytics
                    </button>
                  </div>
                  <div className="border-t my-1" role="separator" />
                  <div className="p-1">
                    <button
                      onClick={handleLogout}
                      className="w-full flex items-center gap-2 px-2 py-1.5 text-sm rounded-sm hover:bg-destructive hover:text-destructive-foreground transition-colors text-destructive"
                      role="menuitem"
                    >
                      <LogOut className="h-4 w-4" aria-hidden="true" />
                      Logout
                    </button>
                  </div>
                </div>
              )}
            </div>
          ) : (
            <div className="flex items-center gap-2">
              <Link to="/login">
                <Button variant="ghost" size="sm">Sign in</Button>
              </Link>
              <Link to="/register">
                <Button size="sm">Sign up</Button>
              </Link>
            </div>
          )}
        </div>
      </div>
    </header>
  );
}
