import { useState, useEffect, useMemo } from 'react';
import {
  CommandDialog,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  CommandSeparator,
} from '@/components/ui/command';
import { useNavigate } from 'react-router-dom';
import {
  LayoutDashboard,
  List,
  BarChart3,
  FileText,
  Settings,
  Plus,
  Moon,
  Sun,
  HelpCircle,
  LogOut,
  Activity,
} from 'lucide-react';
import { useTheme } from '@/hooks/useTheme';
import { useAuth } from '@/contexts/AuthContext';
import { useOnboarding } from '../onboarding/OnboardingProvider';

interface CommandItemData {
  id: string;
  label: string;
  icon: React.ElementType;
  shortcut?: string;
  action: () => void;
  category: string;
}

export function CommandPalette() {
  const [open, setOpen] = useState(false);
  const navigate = useNavigate();
  const { theme, setTheme } = useTheme();
  const { logout } = useAuth();
  const { resetOnboarding } = useOnboarding();

  // Toggle command palette with Cmd/Ctrl + K
  useEffect(() => {
    const down = (e: KeyboardEvent) => {
      if (e.key === 'k' && (e.metaKey || e.ctrlKey)) {
        e.preventDefault();
        setOpen((open) => !open);
      }
    };

    document.addEventListener('keydown', down);
    return () => document.removeEventListener('keydown', down);
  }, []);

  const commands = useMemo<CommandItemData[]>(() => [
    // Navigation
    {
      id: 'dashboard',
      label: 'Go to Dashboard',
      icon: LayoutDashboard,
      shortcut: 'D',
      action: () => {
        navigate('/');
        setOpen(false);
      },
      category: 'Navigation',
    },
    {
      id: 'scenarios',
      label: 'Go to Scenarios',
      icon: List,
      shortcut: 'S',
      action: () => {
        navigate('/scenarios');
        setOpen(false);
      },
      category: 'Navigation',
    },
    {
      id: 'compare',
      label: 'Compare Scenarios',
      icon: BarChart3,
      shortcut: 'C',
      action: () => {
        navigate('/compare');
        setOpen(false);
      },
      category: 'Navigation',
    },
    {
      id: 'reports',
      label: 'View Reports',
      icon: FileText,
      shortcut: 'R',
      action: () => {
        navigate('/');
        setOpen(false);
      },
      category: 'Navigation',
    },
    {
      id: 'analytics',
      label: 'Analytics Dashboard',
      icon: Activity,
      shortcut: 'A',
      action: () => {
        navigate('/analytics');
        setOpen(false);
      },
      category: 'Navigation',
    },
    // Actions
    {
      id: 'new-scenario',
      label: 'Create New Scenario',
      icon: Plus,
      shortcut: 'N',
      action: () => {
        navigate('/scenarios', { state: { openNew: true } });
        setOpen(false);
      },
      category: 'Actions',
    },
    {
      id: 'toggle-theme',
      label: theme === 'dark' ? 'Switch to Light Mode' : 'Switch to Dark Mode',
      icon: theme === 'dark' ? Sun : Moon,
      action: () => {
        setTheme(theme === 'dark' ? 'light' : 'dark');
        setOpen(false);
      },
      category: 'Actions',
    },
    {
      id: 'restart-tour',
      label: 'Restart Onboarding Tour',
      icon: HelpCircle,
      action: () => {
        resetOnboarding();
        setOpen(false);
      },
      category: 'Actions',
    },
    // Settings
    {
      id: 'api-keys',
      label: 'Manage API Keys',
      icon: Settings,
      action: () => {
        navigate('/settings/api-keys');
        setOpen(false);
      },
      category: 'Settings',
    },
    {
      id: 'logout',
      label: 'Logout',
      icon: LogOut,
      action: () => {
        logout();
        setOpen(false);
      },
      category: 'Settings',
    },
  ], [navigate, theme, setTheme, logout, resetOnboarding]);

  // Group commands by category
  const groupedCommands = useMemo(() => {
    const groups: Record<string, CommandItemData[]> = {};
    commands.forEach((cmd) => {
      if (!groups[cmd.category]) {
        groups[cmd.category] = [];
      }
      groups[cmd.category].push(cmd);
    });
    return groups;
  }, [commands]);

  return (
    <CommandDialog open={open} onOpenChange={setOpen}>
      <CommandInput placeholder="Type a command or search..." />
      <CommandList>
        <CommandEmpty>No results found.</CommandEmpty>
        {Object.entries(groupedCommands).map(([category, items], index) => (
          <div key={category}>
            {index > 0 && <CommandSeparator />}
            <CommandGroup heading={category}>
              {items.map((item) => (
                <CommandItem
                  key={item.id}
                  onSelect={item.action}
                  className="flex items-center justify-between"
                >
                  <div className="flex items-center gap-2">
                    <item.icon className="h-4 w-4" />
                    <span>{item.label}</span>
                  </div>
                  {item.shortcut && (
                    <kbd className="px-2 py-0.5 bg-muted rounded text-xs">
                      {item.shortcut}
                    </kbd>
                  )}
                </CommandItem>
              ))}
            </CommandGroup>
          </div>
        ))}
      </CommandList>
    </CommandDialog>
  );
}
