/**
 * Command Menu Component
 *
 * 斜杠命令选择菜单，支持键盘导航
 */

import { useEffect, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Terminal, Sparkles, FolderGit2 } from 'lucide-react';
import clsx from 'clsx';

export interface CommandMenuItem {
  name: string;
  description?: string;
  source: string;
}

interface CommandMenuProps {
  /** 命令列表 */
  commands: CommandMenuItem[];
  /** 是否显示 */
  isOpen: boolean;
  /** 当前选中索引 */
  selectedIndex: number;
  /** 选择命令回调 */
  onSelect: (command: CommandMenuItem) => void;
  /** 关闭菜单回调 */
  onClose: () => void;
  /** 选中索引变化回调 */
  onSelectedIndexChange: (index: number) => void;
  /** 是否正在加载 */
  isLoading?: boolean;
  /** 定位参考点（用于计算菜单位置） */
  anchorRect?: DOMRect | null;
}

// 根据 source 获取图标
function getSourceIcon(source: string) {
  switch (source) {
    case 'builtin':
      return <Terminal size={14} className="text-blue-400" />;
    case 'user':
      return <Sparkles size={14} className="text-purple-400" />;
    case 'project':
      return <FolderGit2 size={14} className="text-green-400" />;
    default:
      return <Terminal size={14} className="text-fg-muted" />;
  }
}

// 根据 source 获取标签颜色
function getSourceBadge(source: string) {
  const colors: Record<string, string> = {
    builtin: 'bg-blue-500/20 text-blue-400',
    user: 'bg-purple-500/20 text-purple-400',
    project: 'bg-green-500/20 text-green-400',
  };
  return colors[source] || 'bg-surface-muted/20 text-fg-muted';
}

export function CommandMenu({
  commands,
  isOpen,
  selectedIndex,
  onSelect,
  onClose,
  onSelectedIndexChange,
  isLoading = false,
}: CommandMenuProps) {
  const menuRef = useRef<HTMLDivElement>(null);
  const selectedRef = useRef<HTMLButtonElement>(null);

  // 滚动选中项到可见区域
  useEffect(() => {
    if (isOpen && selectedRef.current) {
      selectedRef.current.scrollIntoView({
        block: 'nearest',
        behavior: 'smooth',
      });
    }
  }, [selectedIndex, isOpen]);

  // 键盘导航
  useEffect(() => {
    if (!isOpen) return;

    const handleKeyDown = (e: KeyboardEvent) => {
      switch (e.key) {
        case 'ArrowDown':
          e.preventDefault();
          onSelectedIndexChange(
            selectedIndex < commands.length - 1 ? selectedIndex + 1 : 0
          );
          break;
        case 'ArrowUp':
          e.preventDefault();
          onSelectedIndexChange(
            selectedIndex > 0 ? selectedIndex - 1 : commands.length - 1
          );
          break;
        case 'Enter':
          e.preventDefault();
          if (commands[selectedIndex]) {
            onSelect(commands[selectedIndex]);
          }
          break;
        case 'Escape':
          e.preventDefault();
          onClose();
          break;
        case 'Tab':
          e.preventDefault();
          if (commands[selectedIndex]) {
            onSelect(commands[selectedIndex]);
          }
          break;
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, commands, selectedIndex, onSelect, onClose, onSelectedIndexChange]);

  return (
    <AnimatePresence>
      {isOpen && (
        <motion.div
          ref={menuRef}
          initial={{ opacity: 0, y: 8, scale: 0.96 }}
          animate={{ opacity: 1, y: 0, scale: 1 }}
          exit={{ opacity: 0, y: 8, scale: 0.96 }}
          transition={{ duration: 0.15 }}
          className="absolute bottom-full left-0 right-0 mb-2 mx-4 md:mx-0 z-50"
        >
          <div className="bg-surface-subtle border border-line rounded-lg shadow-xl overflow-hidden max-h-64 overflow-y-auto">
            {/* Header */}
            <div className="px-3 py-2 border-b border-line bg-surface-subtle/80 sticky top-0">
              <div className="flex items-center gap-2 text-xs text-fg-muted">
                <Terminal size={12} />
                <span>Commands</span>
                {commands.length > 0 && (
                  <span className="text-fg-subtle">({commands.length})</span>
                )}
              </div>
            </div>

            {/* Loading */}
            {isLoading && commands.length === 0 && (
              <div className="px-3 py-4 text-center text-fg-muted text-sm">
                Loading commands...
              </div>
            )}

            {/* Empty state */}
            {!isLoading && commands.length === 0 && (
              <div className="px-3 py-4 text-center text-fg-muted text-sm">
                No commands found
              </div>
            )}

            {/* Command list */}
            {commands.length > 0 && (
              <div className="py-1">
                {commands.map((command, index) => (
                  <button
                    key={command.name}
                    ref={index === selectedIndex ? selectedRef : null}
                    onClick={() => onSelect(command)}
                    onMouseEnter={() => onSelectedIndexChange(index)}
                    className={clsx(
                      'w-full px-3 py-2 flex items-start gap-3 text-left transition-colors',
                      index === selectedIndex
                        ? 'bg-primary-600/20'
                        : 'hover:bg-surface-muted/50'
                    )}
                  >
                    {/* Icon */}
                    <div className="mt-0.5">{getSourceIcon(command.source)}</div>

                    {/* Content */}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <span
                          className={clsx(
                            'font-mono text-sm',
                            index === selectedIndex
                              ? 'text-primary-300'
                              : 'text-fg-secondary'
                          )}
                        >
                          /{command.name}
                        </span>
                        <span
                          className={clsx(
                            'text-[10px] px-1.5 py-0.5 rounded-full',
                            getSourceBadge(command.source)
                          )}
                        >
                          {command.source}
                        </span>
                      </div>
                      {command.description && (
                        <p className="text-xs text-fg-muted mt-0.5 truncate">
                          {command.description}
                        </p>
                      )}
                    </div>

                    {/* Keyboard hint */}
                    {index === selectedIndex && (
                      <div className="flex items-center gap-1 text-[10px] text-fg-subtle">
                        <kbd className="px-1 py-0.5 bg-surface-muted rounded">
                          Enter
                        </kbd>
                      </div>
                    )}
                  </button>
                ))}
              </div>
            )}

            {/* Footer hint */}
            <div className="px-3 py-1.5 border-t border-line bg-surface-subtle/80 sticky bottom-0">
              <div className="flex items-center gap-3 text-[10px] text-fg-subtle">
                <span>
                  <kbd className="px-1 py-0.5 bg-surface-muted rounded mr-1">↑</kbd>
                  <kbd className="px-1 py-0.5 bg-surface-muted rounded">↓</kbd>
                  {' '}navigate
                </span>
                <span>
                  <kbd className="px-1 py-0.5 bg-surface-muted rounded">Tab</kbd>
                  {' '}select
                </span>
                <span>
                  <kbd className="px-1 py-0.5 bg-surface-muted rounded">Esc</kbd>
                  {' '}close
                </span>
              </div>
            </div>
          </div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
