import { useState, useRef, useEffect } from 'react';
import { ChevronDown, LogOut, Sun, Moon, Monitor, Check } from 'lucide-react';
import { useAuth } from '@/contexts/AuthContext';
import { useTheme, ThemeMode, ColorScheme } from '@/hooks/useTheme';

const modes: { value: ThemeMode; label: string; icon: typeof Sun }[] = [
  { value: 'light', label: 'Light', icon: Sun },
  { value: 'dark', label: 'Dark', icon: Moon },
  { value: 'system', label: 'System', icon: Monitor },
];

const colorSchemes: { value: ColorScheme; label: string; color: string }[] = [
  { value: 'blue', label: 'Blue', color: 'bg-blue-500' },
  { value: 'purple', label: 'Purple', color: 'bg-purple-500' },
  { value: 'green', label: 'Green', color: 'bg-green-500' },
  { value: 'orange', label: 'Orange', color: 'bg-orange-500' },
];

export function UserMenu() {
  const { user, backendUser, logout } = useAuth();
  const { mode, colorScheme, setMode, setColorScheme } = useTheme();
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Close dropdown when clicking outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // Get user display info
  const displayName = backendUser?.name || user?.name || user?.email || 'User';
  const displayEmail = backendUser?.email || user?.email || '';
  const displayRole = backendUser?.role || '';

  // Generate initials for avatar
  const getInitials = (name: string) => {
    if (!name) return 'U';
    const parts = name.split(' ');
    if (parts.length >= 2) {
      return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
    }
    return name.substring(0, 2).toUpperCase();
  };

  const initials = getInitials(displayName);

  // Get role badge color
  const getRoleBadgeColor = (role: string) => {
    switch (role.toUpperCase()) {
      case 'ADMINISTRATOR':
        return 'bg-red-500/10 text-red-600 dark:text-red-400';
      case 'COORDINATOR':
        return 'bg-blue-500/10 text-blue-600 dark:text-blue-400';
      case 'DRIVER':
        return 'bg-green-500/10 text-green-600 dark:text-green-400';
      default:
        return 'bg-muted text-muted-foreground';
    }
  };

  return (
    <div className="relative" ref={dropdownRef}>
      {/* User menu trigger button */}
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-2 px-3 py-2 rounded-lg hover:bg-accent transition-colors"
        style={{ minHeight: '44px' }}
        aria-label="User menu"
        aria-expanded={isOpen}
        aria-haspopup="true"
      >
        {/* Avatar with initials */}
        <div className="flex items-center justify-center w-8 h-8 rounded-full bg-primary text-primary-foreground font-semibold text-sm">
          {initials}
        </div>

        {/* Name (hidden on mobile) */}
        <span className="hidden md:block text-sm font-medium text-foreground max-w-[120px] truncate">
          {displayName}
        </span>

        {/* Chevron icon */}
        <ChevronDown
          className={`h-4 w-4 text-muted-foreground transition-transform ${
            isOpen ? 'rotate-180' : ''
          }`}
        />
      </button>

      {/* Dropdown menu */}
      {isOpen && (
        <div className="absolute right-0 mt-2 w-[280px] rounded-lg bg-popover border border-border shadow-elevated z-50 overflow-hidden animate-in fade-in slide-in-from-top-2 duration-150">
          {/* User info section */}
          <div className="px-4 py-3 border-b border-border">
            <div className="flex items-start gap-3">
              {/* Avatar */}
              <div className="flex items-center justify-center w-10 h-10 rounded-full bg-primary text-primary-foreground font-semibold">
                {initials}
              </div>

              {/* User details */}
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium text-foreground truncate">
                  {displayName}
                </p>
                <p className="text-xs text-muted-foreground truncate mt-0.5">
                  {displayEmail}
                </p>
                {displayRole && (
                  <span
                    className={`inline-block mt-1.5 px-2 py-0.5 text-xs font-medium rounded ${getRoleBadgeColor(
                      displayRole
                    )}`}
                  >
                    {displayRole}
                  </span>
                )}
              </div>
            </div>
          </div>

          {/* Appearance section */}
          <div className="px-4 py-3 border-b border-border">
            <p className="text-xs font-medium text-muted-foreground uppercase tracking-wide mb-2">
              Appearance
            </p>

            {/* Theme mode */}
            <div className="mb-3">
              <p className="text-xs text-muted-foreground mb-1.5">Theme</p>
              <div className="flex gap-1">
                {modes.map(({ value, label, icon: Icon }) => (
                  <button
                    key={value}
                    onClick={() => setMode(value)}
                    className={`flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 rounded text-xs font-medium transition-colors ${
                      mode === value
                        ? 'bg-primary text-primary-foreground'
                        : 'bg-muted hover:bg-accent text-foreground'
                    }`}
                    title={label}
                  >
                    <Icon className="h-3.5 w-3.5" />
                    {label}
                  </button>
                ))}
              </div>
            </div>

            {/* Color scheme */}
            <div>
              <p className="text-xs text-muted-foreground mb-1.5">Color</p>
              <div className="flex gap-2">
                {colorSchemes.map(({ value, label, color }) => (
                  <button
                    key={value}
                    onClick={() => setColorScheme(value)}
                    className={`relative w-8 h-8 rounded-full ${color} transition-all hover:scale-110 ${
                      colorScheme === value
                        ? 'ring-2 ring-offset-2 ring-offset-popover ring-foreground scale-110'
                        : ''
                    }`}
                    title={label}
                    aria-label={`${label} color scheme`}
                  >
                    {colorScheme === value && (
                      <Check className="absolute inset-0 m-auto h-3.5 w-3.5 text-white drop-shadow-sm" />
                    )}
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* Sign out section */}
          <div className="p-2">
            <button
              onClick={() => {
                setIsOpen(false);
                logout();
              }}
              className="w-full flex items-center gap-3 px-3 py-2 rounded text-sm font-medium text-destructive hover:bg-destructive/10 transition-colors"
            >
              <LogOut className="h-4 w-4" />
              Sign Out
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
