import { useState, useEffect, useMemo } from 'react';
import { Dialog, DialogContent } from './ui/dialog';
import { Input } from './ui/input';
import { ScrollArea } from './ui/scroll-area';
import {
  MagnifyingGlass,
  FileCode,
  FolderPlus,
  Play,
  Copy,
  Download,
  Trash,
  Rocket,
  Bug,
} from '@phosphor-icons/react';

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

interface CommandPaletteProps {
  open: boolean;
  onClose: () => void;
  commands: Command[];
}

export function CommandPalette({ open, onClose, commands }: CommandPaletteProps) {
  const [search, setSearch] = useState('');
  const [selectedIndex, setSelectedIndex] = useState(0);

  // Filter commands based on search
  const filteredCommands = useMemo(() => {
    if (!search) return commands;

    const searchLower = search.toLowerCase();
    return commands.filter(
      (cmd) =>
        cmd.label.toLowerCase().includes(searchLower) ||
        cmd.description.toLowerCase().includes(searchLower) ||
        cmd.keywords?.some((k) => k.toLowerCase().includes(searchLower))
    );
  }, [commands, search]);

  // Reset when opened/closed
  useEffect(() => {
    if (open) {
      setSearch('');
      setSelectedIndex(0);
    }
  }, [open]);

  // Keyboard navigation
  useEffect(() => {
    if (!open) return;

    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'ArrowDown') {
        e.preventDefault();
        setSelectedIndex((prev) => Math.min(prev + 1, filteredCommands.length - 1));
      } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        setSelectedIndex((prev) => Math.max(prev - 1, 0));
      } else if (e.key === 'Enter') {
        e.preventDefault();
        if (filteredCommands[selectedIndex]) {
          handleExecute(filteredCommands[selectedIndex]);
        }
      }
    };

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

  const handleExecute = (command: Command) => {
    command.action();
    onClose();
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl p-0 gap-0">
        <div className="flex items-center gap-3 px-4 py-3 border-b border-border">
          <Rocket className="text-muted-foreground" size={20} />
          <Input
            value={search}
            onChange={(e) => {
              setSearch(e.target.value);
              setSelectedIndex(0);
            }}
            placeholder="Type a command or search..."
            className="border-0 focus-visible:ring-0 focus-visible:ring-offset-0 text-base"
            autoFocus
          />
        </div>

        <ScrollArea className="max-h-[400px]">
          {filteredCommands.length === 0 ? (
            <div className="py-12 text-center text-muted-foreground">
              <MagnifyingGlass size={48} className="mx-auto mb-3 opacity-50" />
              <p className="text-sm">No commands found</p>
              {search && (
                <p className="text-xs mt-1">Try a different search term</p>
              )}
            </div>
          ) : (
            <div className="py-2">
              {filteredCommands.map((command, index) => (
                <button
                  key={command.id}
                  onClick={() => handleExecute(command)}
                  className={`w-full px-4 py-3 flex items-center gap-3 hover:bg-accent/50 transition-colors ${
                    index === selectedIndex ? 'bg-accent/50' : ''
                  }`}
                  onMouseEnter={() => setSelectedIndex(index)}
                >
                  <div className="flex-shrink-0 text-accent">{command.icon}</div>
                  <div className="flex-1 text-left">
                    <div className="text-sm font-medium">{command.label}</div>
                    <div className="text-xs text-muted-foreground">
                      {command.description}
                    </div>
                  </div>
                  {index === selectedIndex && (
                    <kbd className="px-2 py-1 text-xs bg-muted rounded">↵</kbd>
                  )}
                </button>
              ))}
            </div>
          )}
        </ScrollArea>

        <div className="px-4 py-2 border-t border-border bg-muted/30 flex items-center justify-between 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-background rounded">↑↓</kbd> Navigate
            </span>
            <span className="flex items-center gap-1">
              <kbd className="px-1.5 py-0.5 bg-background rounded">↵</kbd> Execute
            </span>
            <span className="flex items-center gap-1">
              <kbd className="px-1.5 py-0.5 bg-background rounded">Esc</kbd> Close
            </span>
          </div>
          <span>{filteredCommands.length} commands</span>
        </div>
      </DialogContent>
    </Dialog>
  );
}

// Predefined command templates
export const createDefaultCommands = (actions: {
  onNewProject: () => void;
  onTemplates: () => void;
  onPreview: () => void;
  onExport: () => void;
  onCopy: () => void;
}): Command[] => [
  {
    id: 'new-project',
    label: 'New Project',
    description: 'Create a new project from template',
    icon: <FolderPlus size={20} />,
    action: actions.onNewProject,
    keywords: ['create', 'start', 'begin'],
  },
  {
    id: 'templates',
    label: 'Browse Templates',
    description: 'View and select code templates',
    icon: <FileCode size={20} />,
    action: actions.onTemplates,
    keywords: ['snippets', 'examples', 'boilerplate'],
  },
  {
    id: 'preview',
    label: 'Preview All Platforms',
    description: 'Open multi-platform preview',
    icon: <Play size={20} />,
    action: actions.onPreview,
    keywords: ['run', 'test', 'demo'],
  },
  {
    id: 'copy',
    label: 'Copy Code',
    description: 'Copy current code to clipboard',
    icon: <Copy size={20} />,
    action: actions.onCopy,
    keywords: ['clipboard', 'paste'],
  },
  {
    id: 'export',
    label: 'Export Script',
    description: 'Download code as .lua file',
    icon: <Download size={20} />,
    action: actions.onExport,
    keywords: ['download', 'save', 'file'],
  },
];
