/**
 * Agent Mode Selector Component
 *
 * 在 ChatInput 左侧显示，用于切换 Build/Plan 模式和控制 Auto-approve
 */

import { useState, useRef, useEffect } from 'react';
import { Hammer, FileSearch, ChevronDown, Check } from 'lucide-react';
import clsx from 'clsx';
import { Switch } from '../primitives/Switch.js';

export type AgentModeType = 'build' | 'plan';

interface AgentModeSelectorProps {
  /** 当前模式 */
  mode: AgentModeType;
  /** 模式变更回调 */
  onModeChange: (mode: AgentModeType) => void;
  /** 是否自动授权文件写入/编辑 */
  autoApprove: boolean;
  /** 自动授权变更回调 */
  onAutoApproveChange: (enabled: boolean) => void;
  /** 是否禁用 */
  disabled?: boolean;
}

const modeConfig = {
  build: {
    label: 'Build',
    icon: Hammer,
    color: 'text-blue-500',
    bgColor: 'bg-blue-500/10',
    description: '可执行代码修改',
  },
  plan: {
    label: 'Plan',
    icon: FileSearch,
    color: 'text-purple-500',
    bgColor: 'bg-purple-500/10',
    description: '只读模式，仅分析',
  },
};

export function AgentModeSelector({
  mode,
  onModeChange,
  autoApprove,
  onAutoApproveChange,
  disabled = false,
}: AgentModeSelectorProps) {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  const currentMode = modeConfig[mode];
  const ModeIcon = currentMode.icon;

  // 点击外部关闭下拉菜单
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    }

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
      return () => document.removeEventListener('mousedown', handleClickOutside);
    }
  }, [isOpen]);

  // 键盘导航
  useEffect(() => {
    function handleKeyDown(event: KeyboardEvent) {
      if (!isOpen) return;

      if (event.key === 'Escape') {
        setIsOpen(false);
      } else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
        event.preventDefault();
        // 切换模式
        onModeChange(mode === 'build' ? 'plan' : 'build');
      } else if (event.key === 'Enter') {
        setIsOpen(false);
      }
    }

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, mode, onModeChange]);

  const handleModeSelect = (newMode: AgentModeType) => {
    onModeChange(newMode);
    setIsOpen(false);
  };

  return (
    <div className="flex items-center gap-2">
      {/* 模式选择器 */}
      <div ref={dropdownRef} className="relative">
        <button
          type="button"
          onClick={() => !disabled && setIsOpen(!isOpen)}
          disabled={disabled}
          className={clsx(
            'flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg border transition-colors',
            'text-sm font-medium',
            disabled
              ? 'opacity-50 cursor-not-allowed border-line bg-surface-subtle'
              : 'border-line hover:border-line-strong hover:bg-surface-subtle cursor-pointer',
            currentMode.color
          )}
        >
          <ModeIcon size={16} />
          <span className="hidden sm:inline">{currentMode.label}</span>
          <ChevronDown
            size={14}
            className={clsx(
              'transition-transform text-fg-muted',
              isOpen && 'rotate-180'
            )}
          />
        </button>

        {/* 下拉菜单 */}
        {isOpen && (
          <div className="absolute bottom-full left-0 mb-1 w-48 py-1 bg-surface-base border border-line rounded-lg shadow-lg z-50">
            {(Object.entries(modeConfig) as [AgentModeType, typeof modeConfig.build][]).map(
              ([modeKey, config]) => {
                const Icon = config.icon;
                const isSelected = modeKey === mode;

                return (
                  <button
                    key={modeKey}
                    type="button"
                    onClick={() => handleModeSelect(modeKey)}
                    className={clsx(
                      'w-full flex items-center gap-2.5 px-3 py-2 text-left transition-colors',
                      isSelected
                        ? `${config.bgColor} ${config.color}`
                        : 'hover:bg-surface-subtle text-fg'
                    )}
                  >
                    <Icon size={16} className={config.color} />
                    <div className="flex-1">
                      <div className="text-sm font-medium">{config.label}</div>
                      <div className="text-xs text-fg-muted">{config.description}</div>
                    </div>
                    {isSelected && <Check size={16} className={config.color} />}
                  </button>
                );
              }
            )}
          </div>
        )}
      </div>

      {/* Auto-approve 开关 - 仅在 Build 模式下显示 */}
      {mode === 'build' && (
        <div
          className={clsx(
            'flex items-center gap-1.5 px-2 py-1 rounded-lg transition-colors',
            autoApprove ? 'bg-orange-500/10' : 'bg-transparent'
          )}
          title={autoApprove ? '自动授权已开启：文件写入/编辑无需确认' : '点击开启自动授权'}
        >
          <span
            className={clsx(
              'text-xs hidden sm:inline transition-colors',
              autoApprove ? 'text-orange-500' : 'text-fg-muted'
            )}
          >
            Auto Edit
          </span>
          <Switch
            checked={autoApprove}
            onCheckedChange={onAutoApproveChange}
            disabled={disabled}
            className="scale-75 origin-left"
          />
        </div>
      )}
    </div>
  );
}
