/**
 * VEZA V5 ULTRA - COMMAND PALETTE
 * Quick navigation and actions with Cmd+K
 */

import { useState, useEffect, useCallback, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useNavigate } from 'react-router-dom';
import { 
  Home, 
  Music, 
  MessageSquare, 
  Settings, 
  User, 
  Search,
  Play,
  Pause,
  SkipForward,
  Volume2,
  LogOut
} from 'lucide-react';
import { cn } from '@/lib/utils';

interface Command {
  id: string;
  label: string;
  description?: string;
  icon?: React.ReactNode;
  action: () => void;
  keywords?: string[];
  shortcut?: string;
}

interface CommandPaletteProps {
  isOpen: boolean;
  onClose: () => void;
}

export function CommandPalette({ isOpen, onClose }: CommandPaletteProps) {
  const [search, setSearch] = useState('');
  const [selectedIndex, setSelectedIndex] = useState(0);
  const navigate = useNavigate();
  const inputRef = useRef<HTMLInputElement>(null);

  // Define commands
  const commands: Command[] = [
    {
      id: 'dashboard',
      label: 'Go to Dashboard',
      description: 'View your dashboard',
      icon: <Home className="w-4 h-4" />,
      action: () => navigate('/dashboard'),
      keywords: ['home', 'dashboard', 'main'],
      shortcut: '⌘D',
    },
    {
      id: 'library',
      label: 'Go to Library',
      description: 'Browse your music library',
      icon: <Music className="w-4 h-4" />,
      action: () => navigate('/library'),
      keywords: ['music', 'library', 'tracks', 'songs'],
      shortcut: '⌘L',
    },
    {
      id: 'chat',
      label: 'Go to Chat',
      description: 'Open chat interface',
      icon: <MessageSquare className="w-4 h-4" />,
      action: () => navigate('/chat'),
      keywords: ['chat', 'message', 'talk'],
      shortcut: '⌘C',
    },
    {
      id: 'stream',
      label: 'Go to Stream',
      description: 'Access streaming page',
      icon: <Play className="w-4 h-4" />,
      action: () => navigate('/stream'),
      keywords: ['stream', 'play', 'audio'],
      shortcut: '⌘S',
    },
    {
      id: 'settings',
      label: 'Go to Settings',
      description: 'Manage your preferences',
      icon: <Settings className="w-4 h-4" />,
      action: () => navigate('/settings'),
      keywords: ['settings', 'preferences', 'config'],
      shortcut: '⌘,',
    },
    {
      id: 'profile',
      label: 'Go to Profile',
      description: 'View your profile',
      icon: <User className="w-4 h-4" />,
      action: () => navigate('/profile'),
      keywords: ['profile', 'account', 'user'],
      shortcut: '⌘P',
    },
  ];

  // Filter commands based on search
  const filteredCommands = commands.filter(command => {
    const searchLower = search.toLowerCase();
    return (
      command.label.toLowerCase().includes(searchLower) ||
      command.description?.toLowerCase().includes(searchLower) ||
      command.keywords?.some(k => k.includes(searchLower))
    );
  });

  // Handle keyboard navigation
  const handleKeyDown = useCallback(
    (e: KeyboardEvent) => {
      if (!isOpen) return;

      switch (e.key) {
        case 'ArrowDown':
          e.preventDefault();
          setSelectedIndex(prev =>
            prev < filteredCommands.length - 1 ? prev + 1 : prev
          );
          break;
        case 'ArrowUp':
          e.preventDefault();
          setSelectedIndex(prev => (prev > 0 ? prev - 1 : 0));
          break;
        case 'Enter':
          e.preventDefault();
          if (filteredCommands[selectedIndex]) {
            filteredCommands[selectedIndex].action();
            onClose();
          }
          break;
        case 'Escape':
          e.preventDefault();
          onClose();
          break;
      }
    },
    [isOpen, filteredCommands, selectedIndex, onClose]
  );

  useEffect(() => {
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [handleKeyDown]);

  // Focus input when opened
  useEffect(() => {
    if (isOpen && inputRef.current) {
      inputRef.current.focus();
    }
  }, [isOpen]);

  // Reset search when opening
  useEffect(() => {
    if (isOpen) {
      setSearch('');
      setSelectedIndex(0);
    }
  }, [isOpen]);

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          {/* Backdrop */}
          <motion.div
            className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={onClose}
          />

          {/* Command Palette */}
          <div className="fixed inset-0 z-50 flex items-start justify-center pt-[20vh] pointer-events-none">
            <motion.div
              className="w-full max-w-2xl pointer-events-auto"
              initial={{ opacity: 0, scale: 0.95, y: -20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: -20 }}
              transition={{ type: 'spring', duration: 0.3 }}
            >
              <div className="glass-strong rounded-3xl shadow-2xl overflow-hidden border border-white/10">
                {/* Search Input */}
                <div className="flex items-center gap-3 px-6 py-4 border-b border-white/10">
                  <Search className="w-5 h-5 text-muted-foreground" />
                  <input
                    ref={inputRef}
                    type="text"
                    value={search}
                    onChange={e => setSearch(e.target.value)}
                    placeholder="Type a command or search..."
                    className="flex-1 bg-transparent outline-none text-lg placeholder:text-muted-foreground"
                  />
                  <kbd className="hidden sm:inline-block px-2 py-1 text-xs font-semibold text-muted-foreground bg-white/5 rounded border border-white/10">
                    ESC
                  </kbd>
                </div>

                {/* Commands List */}
                <div className="max-h-96 overflow-y-auto scrollbar-thin p-2">
                  {filteredCommands.length === 0 ? (
                    <div className="py-12 text-center text-muted-foreground">
                      No commands found
                    </div>
                  ) : (
                    <div className="space-y-1">
                      {filteredCommands.map((command, index) => (
                        <motion.button
                          key={command.id}
                          onClick={() => {
                            command.action();
                            onClose();
                          }}
                          onMouseEnter={() => setSelectedIndex(index)}
                          className={cn(
                            'w-full flex items-center gap-4 px-4 py-3 rounded-xl transition-smooth',
                            'hover:bg-white/10 focus:outline-none',
                            selectedIndex === index &&
                              'bg-white/10 shadow-lg'
                          )}
                          initial={{ opacity: 0, x: -10 }}
                          animate={{ opacity: 1, x: 0 }}
                          transition={{ delay: index * 0.03 }}
                        >
                          {/* Icon */}
                          <div className="flex-shrink-0 w-10 h-10 rounded-lg bg-gradient-brand flex items-center justify-center">
                            {command.icon}
                          </div>

                          {/* Text */}
                          <div className="flex-1 text-left">
                            <div className="font-medium">
                              {command.label}
                            </div>
                            {command.description && (
                              <div className="text-sm text-muted-foreground">
                                {command.description}
                              </div>
                            )}
                          </div>

                          {/* Shortcut */}
                          {command.shortcut && (
                            <kbd className="hidden sm:inline-block px-2 py-1 text-xs font-semibold text-muted-foreground bg-white/5 rounded border border-white/10">
                              {command.shortcut}
                            </kbd>
                          )}
                        </motion.button>
                      ))}
                    </div>
                  )}
                </div>

                {/* Footer */}
                <div className="flex items-center justify-between px-6 py-3 border-t border-white/10 text-xs text-muted-foreground">
                  <div className="flex items-center gap-4">
                    <span className="flex items-center gap-1">
                      <kbd className="px-1.5 py-0.5 bg-white/5 rounded border border-white/10">
                        ↑↓
                      </kbd>
                      Navigate
                    </span>
                    <span className="flex items-center gap-1">
                      <kbd className="px-1.5 py-0.5 bg-white/5 rounded border border-white/10">
                        ⏎
                      </kbd>
                      Select
                    </span>
                  </div>
                  <span>Veza V5 Ultra</span>
                </div>
              </div>
            </motion.div>
          </div>
        </>
      )}
    </AnimatePresence>
  );
}

// Hook to use command palette
export function useCommandPalette() {
  const [isOpen, setIsOpen] = useState(false);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        setIsOpen(prev => !prev);
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, []);

  return {
    isOpen,
    open: () => setIsOpen(true),
    close: () => setIsOpen(false),
    toggle: () => setIsOpen(prev => !prev),
  };
}

