'use client';

import * as React from 'react';
import { Command } from 'lucide-react';
import { cn } from '@/lib/utils/cn';

export interface CommandAction {
  id: string;
  label: string;
  description?: string;
  shortcut?: string;
  category: 'edit' | 'playback' | 'file' | 'view' | 'effects';
  action: () => void;
}

export interface CommandPaletteProps {
  actions: CommandAction[];
  className?: string;
}

export function CommandPalette({ actions, className }: CommandPaletteProps) {
  const [isOpen, setIsOpen] = React.useState(false);
  const [search, setSearch] = React.useState('');
  const [selectedIndex, setSelectedIndex] = React.useState(0);
  const inputRef = React.useRef<HTMLInputElement>(null);

  const filteredActions = React.useMemo(() => {
    if (!search) return actions;
    const query = search.toLowerCase();
    return actions.filter(
      (action) =>
        action.label.toLowerCase().includes(query) ||
        action.description?.toLowerCase().includes(query) ||
        action.category.toLowerCase().includes(query)
    );
  }, [actions, search]);

  const groupedActions = React.useMemo(() => {
    const groups: Record<string, CommandAction[]> = {};
    filteredActions.forEach((action) => {
      if (!groups[action.category]) {
        groups[action.category] = [];
      }
      groups[action.category].push(action);
    });
    return groups;
  }, [filteredActions]);

  React.useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Ctrl+K or Cmd+K to open
      if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault();
        setIsOpen(true);
      }
      // Escape to close
      if (e.key === 'Escape') {
        setIsOpen(false);
        setSearch('');
        setSelectedIndex(0);
      }
    };

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

  React.useEffect(() => {
    if (isOpen && inputRef.current) {
      inputRef.current.focus();
    }
  }, [isOpen]);

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

  const executeAction = (action: CommandAction) => {
    action.action();
    setIsOpen(false);
    setSearch('');
    setSelectedIndex(0);
  };

  if (!isOpen) {
    return (
      <button
        onClick={() => setIsOpen(true)}
        className={cn(
          'h-9 w-9 rounded-md',
          'inline-flex items-center justify-center',
          'hover:bg-accent hover:text-accent-foreground',
          'transition-colors',
          className
        )}
        title="Command Palette (Ctrl+K)"
      >
        <Command className="h-5 w-5" />
      </button>
    );
  }

  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center p-4 sm:p-8 bg-black/50 backdrop-blur-sm">
      <div
        className={cn(
          'w-full max-w-2xl mt-20 bg-card rounded-lg border-2 border-border shadow-2xl',
          'animate-slideInFromTop',
          className
        )}
      >
        {/* Search Input */}
        <div className="flex items-center gap-3 p-4 border-b border-border">
          <Command className="h-5 w-5 text-muted-foreground" />
          <input
            ref={inputRef}
            type="text"
            value={search}
            onChange={(e) => {
              setSearch(e.target.value);
              setSelectedIndex(0);
            }}
            onKeyDown={handleKeyDown}
            placeholder="Type a command or search..."
            className="flex-1 bg-transparent border-none outline-none text-foreground placeholder:text-muted-foreground"
          />
          <kbd className="px-2 py-1 text-xs bg-muted rounded border border-border">
            ESC
          </kbd>
        </div>

        {/* Results */}
        <div className="max-h-96 overflow-y-auto p-2">
          {Object.keys(groupedActions).length === 0 ? (
            <div className="p-8 text-center text-muted-foreground text-sm">
              No commands found
            </div>
          ) : (
            Object.entries(groupedActions).map(([category, categoryActions]) => (
              <div key={category} className="mb-4 last:mb-0">
                <div className="px-2 py-1 text-xs font-semibold text-muted-foreground uppercase">
                  {category}
                </div>
                {categoryActions.map((action, index) => {
                  const globalIndex = filteredActions.indexOf(action);
                  return (
                    <button
                      key={action.id}
                      onClick={() => executeAction(action)}
                      className={cn(
                        'w-full flex items-center justify-between gap-4 px-3 py-2.5 rounded-md',
                        'hover:bg-secondary/50 transition-colors text-left',
                        globalIndex === selectedIndex && 'bg-secondary'
                      )}
                    >
                      <div className="flex-1 min-w-0">
                        <div className="text-sm font-medium text-foreground">
                          {action.label}
                        </div>
                        {action.description && (
                          <div className="text-xs text-muted-foreground truncate">
                            {action.description}
                          </div>
                        )}
                      </div>
                      {action.shortcut && (
                        <kbd className="px-2 py-1 text-xs bg-muted rounded border border-border whitespace-nowrap">
                          {action.shortcut}
                        </kbd>
                      )}
                    </button>
                  );
                })}
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
}
