/**
 * AgentEditor Component
 *
 * Agent 创建/编辑器：配置 Agent 的各项参数
 */

import { useState, useEffect } from 'react';
import {
  X,
  Save,
  Bot,
  ChevronDown,
  ChevronRight,
  AlertCircle,
  Lock,
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { toast } from 'sonner';
import { cn } from '../utils/cn';
import { modalOverlay, modalContent, smoothTransition } from '../utils/animations';
import { Button } from '../primitives/Button';
import {
  getAgent,
  createAgent,
  updateAgent,
  type AgentInput,
  type AgentMode,
  type AgentModelConfig,
  type AgentToolConfig,
} from '../api/client.js';

interface AgentEditorProps {
  /** 编辑现有 Agent 的名称（新建时为 undefined） */
  agentName?: string;
  /** 新建时的默认名称 */
  defaultName?: string;
  /** 复制自哪个 Agent */
  copyFrom?: string;
  onClose: () => void;
  onSave: () => void;
  /** 是否启用响应式布局 */
  responsive?: boolean;
}

// 可折叠区域组件
function CollapsibleSection({
  title,
  children,
  defaultOpen = false,
}: {
  title: string;
  children: React.ReactNode;
  defaultOpen?: boolean;
}) {
  const [isOpen, setIsOpen] = useState(defaultOpen);

  return (
    <div className="border border-line rounded-lg overflow-hidden">
      <button
        type="button"
        className="w-full flex items-center justify-between p-3 bg-surface-subtle/50 hover:bg-surface-subtle transition-colors"
        onClick={() => setIsOpen(!isOpen)}
      >
        <span className="font-medium text-sm">{title}</span>
        {isOpen ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
      </button>
      <AnimatePresence>
        {isOpen && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.2 }}
          >
            <div className="p-4 border-t border-line space-y-4">{children}</div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

export function AgentEditor({
  agentName,
  defaultName = '',
  copyFrom,
  onClose,
  onSave,
  responsive = false,
}: AgentEditorProps) {
  const isNewAgent = !agentName;

  // 表单状态
  const [name, setName] = useState(defaultName);
  const [description, setDescription] = useState('');
  const [mode, setMode] = useState<AgentMode>('primary');

  // 是否为内部 Agent（Internal Agent 只能编辑模型配置）
  const isInternalAgent = mode === 'internal';
  const [prompt, setPrompt] = useState('');
  const [maxSteps, setMaxSteps] = useState<number | undefined>(undefined);

  // 模型配置
  const [modelProvider, setModelProvider] = useState<string>('');
  const [modelName, setModelName] = useState('');
  const [temperature, setTemperature] = useState<number | undefined>(undefined);
  const [maxTokens, setMaxTokens] = useState<number | undefined>(undefined);

  // 工具配置
  const [toolMode, setToolMode] = useState<'all' | 'enabled' | 'disabled'>('all');
  const [toolList, setToolList] = useState('');
  const [noTask, setNoTask] = useState(false);

  // UI 状态
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 加载现有 Agent 数据
  useEffect(() => {
    const loadAgent = async () => {
      const targetName = agentName || copyFrom;
      if (!targetName) return;

      setLoading(true);
      try {
        const result = await getAgent(targetName);
        if (result.success && result.data) {
          const agent = result.data;

          if (!agentName) {
            // 复制模式：不复制名称
            setName(defaultName);
          } else {
            setName(agent.name);
          }

          setDescription(agent.description);
          setMode(agent.mode);
          setPrompt(agent.prompt || '');
          setMaxSteps(agent.maxSteps);

          // 模型配置
          if (agent.model) {
            setModelProvider(agent.model.provider || '');
            setModelName(agent.model.model || '');
            setTemperature(agent.model.temperature);
            setMaxTokens(agent.model.maxTokens);
          }

          // 工具配置
          if (agent.tools) {
            if (agent.tools.enabled && agent.tools.enabled.length > 0) {
              setToolMode('enabled');
              setToolList(agent.tools.enabled.join(', '));
            } else if (agent.tools.disabled && agent.tools.disabled.length > 0) {
              setToolMode('disabled');
              setToolList(agent.tools.disabled.join(', '));
            } else {
              setToolMode('all');
            }
            setNoTask(agent.tools.noTask || false);
          }
        } else {
          setError(result.error || 'Failed to load agent');
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load agent');
      } finally {
        setLoading(false);
      }
    };

    loadAgent();
  }, [agentName, copyFrom, defaultName]);

  // 构建配置对象
  const buildConfig = (): AgentInput => {
    const config: AgentInput = {
      description,
      mode,
    };

    if (prompt.trim()) {
      config.prompt = prompt;
    }

    if (maxSteps !== undefined) {
      config.maxSteps = maxSteps;
    }

    // 模型配置
    const model: AgentModelConfig = {};
    if (modelProvider) {
      model.provider = modelProvider as 'anthropic' | 'deepseek' | 'openai';
    }
    if (modelName) {
      model.model = modelName;
    }
    if (temperature !== undefined) {
      model.temperature = temperature;
    }
    if (maxTokens !== undefined) {
      model.maxTokens = maxTokens;
    }
    if (Object.keys(model).length > 0) {
      config.model = model;
    }

    // 工具配置
    const tools: AgentToolConfig = {};
    if (toolMode === 'enabled' && toolList.trim()) {
      tools.enabled = toolList.split(',').map((t) => t.trim()).filter(Boolean);
    } else if (toolMode === 'disabled' && toolList.trim()) {
      tools.disabled = toolList.split(',').map((t) => t.trim()).filter(Boolean);
    }
    if (noTask) {
      tools.noTask = true;
    }
    if (Object.keys(tools).length > 0) {
      config.tools = tools;
    }

    return config;
  };

  // 保存
  const handleSave = async () => {
    // 验证
    if (!name.trim()) {
      setError('Agent name is required');
      return;
    }
    if (!description.trim()) {
      setError('Description is required');
      return;
    }

    setSaving(true);
    setError(null);

    try {
      const config = buildConfig();

      let result;
      if (isNewAgent) {
        result = await createAgent(name.trim(), config);
      } else {
        result = await updateAgent(name.trim(), config);
      }

      if (result.success) {
        toast.success(isNewAgent ? `Agent "${name}" created` : `Agent "${name}" updated`);
        onSave();
      } else {
        setError(result.error || 'Save failed');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Save failed');
    } finally {
      setSaving(false);
    }
  };

  return (
    <AnimatePresence>
      <motion.div
        variants={modalOverlay}
        initial="initial"
        animate="animate"
        exit="exit"
        transition={{ duration: 0.2 }}
        className={cn(
          'fixed inset-0 bg-black/50 flex z-50',
          responsive ? 'items-end md:items-center justify-center' : 'items-center justify-center'
        )}
        onClick={onClose}
      >
        <motion.div
          variants={modalContent}
          initial="initial"
          animate="animate"
          exit="exit"
          transition={smoothTransition}
          onClick={(e) => e.stopPropagation()}
          className={cn(
            'bg-surface-subtle max-h-[90vh] overflow-hidden flex flex-col',
            responsive
              ? 'w-full md:w-full md:max-w-2xl md:mx-4 rounded-t-2xl md:rounded-lg'
              : 'rounded-lg w-full max-w-2xl mx-4'
          )}
        >
          {/* Header */}
          <div
            className={cn(
              'flex items-center justify-between border-b border-line',
              responsive ? 'px-4 md:px-6 py-4' : 'px-6 py-4'
            )}
          >
            {responsive && (
              <div className="absolute top-2 left-1/2 -translate-x-1/2 w-10 h-1 bg-surface-emphasis rounded-full md:hidden" />
            )}
            <div className={cn(responsive && 'mt-2 md:mt-0')}>
              <h2 className="text-lg font-semibold flex items-center gap-2">
                {isInternalAgent ? (
                  <Lock size={20} className="text-slate-400" />
                ) : (
                  <Bot size={20} className="text-primary-400" />
                )}
                {isNewAgent ? 'Create Agent' : `Edit: ${agentName}`}
                {isInternalAgent && (
                  <span className="text-xs px-2 py-0.5 bg-slate-500/20 text-slate-400 rounded">
                    System
                  </span>
                )}
              </h2>
              {copyFrom && (
                <p className="text-xs text-fg-subtle">Copying from: {copyFrom}</p>
              )}
              {isInternalAgent && (
                <p className="text-xs text-slate-400 mt-1">
                  System agents can only modify model configuration
                </p>
              )}
            </div>
            <div className="flex items-center gap-2">
              <Button
                variant="default"
                size="sm"
                onClick={handleSave}
                disabled={saving || loading}
                className={cn(responsive && 'min-h-[44px]')}
              >
                <Save size={16} className="mr-1" />
                {saving ? 'Saving...' : 'Save'}
              </Button>
              <Button
                variant="ghost"
                size="icon"
                onClick={onClose}
                className={cn(responsive && 'min-w-[44px] min-h-[44px]')}
              >
                <X size={20} />
              </Button>
            </div>
          </div>

          {/* Content */}
          <div className="flex-1 overflow-y-auto p-4 space-y-4">
            {loading ? (
              <div className="flex items-center justify-center py-12">
                <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary-500" />
              </div>
            ) : (
              <>
                {/* Error */}
                {error && (
                  <div className="flex items-start gap-2 p-3 bg-red-500/10 border border-red-500/30 rounded-lg text-red-400 text-sm">
                    <AlertCircle size={16} className="mt-0.5 flex-shrink-0" />
                    <span>{error}</span>
                  </div>
                )}

                {/* Basic Info */}
                <div className="space-y-4">
                  <h3 className="text-sm font-medium text-fg-secondary">Basic Information</h3>

                  {/* Name */}
                  <div>
                    <label className="block text-xs text-fg-muted mb-1">Name *</label>
                    <input
                      type="text"
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                      disabled={!isNewAgent || isInternalAgent}
                      placeholder="my-agent"
                      className={cn(
                        'w-full px-3 py-2 bg-surface-base border border-line rounded-lg text-sm',
                        'focus:outline-none focus:border-primary-500',
                        (!isNewAgent || isInternalAgent) && 'opacity-50 cursor-not-allowed'
                      )}
                    />
                    {!isNewAgent && (
                      <p className="text-xs text-fg-subtle mt-1">Name cannot be changed after creation</p>
                    )}
                  </div>

                  {/* Description */}
                  <div>
                    <label className="block text-xs text-fg-muted mb-1">Description *</label>
                    <input
                      type="text"
                      value={description}
                      onChange={(e) => setDescription(e.target.value)}
                      disabled={isInternalAgent}
                      placeholder="A helpful coding assistant"
                      className={cn(
                        'w-full px-3 py-2 bg-surface-base border border-line rounded-lg text-sm focus:outline-none focus:border-primary-500',
                        isInternalAgent && 'opacity-50 cursor-not-allowed'
                      )}
                    />
                  </div>

                  {/* Mode - 不为内部 Agent 显示 */}
                  {!isInternalAgent && (
                    <div>
                      <label className="block text-xs text-fg-muted mb-1">Mode *</label>
                      <div className="flex gap-2">
                        {(['primary', 'subagent', 'all'] as const).map((m) => (
                          <button
                            key={m}
                            type="button"
                            onClick={() => setMode(m)}
                            className={cn(
                              'px-3 py-2 rounded-lg text-sm transition-colors',
                              mode === m
                                ? 'bg-primary-500 text-white'
                                : 'bg-surface-base text-fg-muted hover:bg-surface-subtle'
                            )}
                          >
                            {m === 'primary' ? 'Primary' : m === 'subagent' ? 'Subagent' : 'Both'}
                          </button>
                        ))}
                      </div>
                      <p className="text-xs text-fg-subtle mt-1">
                        {mode === 'primary'
                          ? 'Can be used as the main agent'
                          : mode === 'subagent'
                          ? 'Can only be spawned by other agents'
                          : 'Can be used in both modes'}
                      </p>
                    </div>
                  )}

                  {/* Internal Mode 显示只读标签 */}
                  {isInternalAgent && (
                    <div>
                      <label className="block text-xs text-fg-muted mb-1">Mode</label>
                      <div className="px-3 py-2 bg-slate-500/10 border border-slate-600/30 rounded-lg text-sm text-slate-400 inline-flex items-center gap-2">
                        <Lock size={14} />
                        Internal (System Agent)
                      </div>
                      <p className="text-xs text-fg-subtle mt-1">
                        System agents are used internally and cannot be called directly
                      </p>
                    </div>
                  )}
                </div>

                {/* System Prompt - 不为内部 Agent 显示 */}
                {!isInternalAgent && (
                  <CollapsibleSection title="System Prompt" defaultOpen={!!prompt}>
                    <div>
                      <textarea
                        value={prompt}
                        onChange={(e) => setPrompt(e.target.value)}
                        placeholder="You are a helpful assistant..."
                        rows={8}
                        className="w-full px-3 py-2 bg-surface-base border border-line rounded-lg text-sm font-mono focus:outline-none focus:border-primary-500 resize-y"
                      />
                      <p className="text-xs text-fg-subtle mt-1">
                        Custom system prompt for this agent. Leave empty to use defaults.
                      </p>
                    </div>
                  </CollapsibleSection>
                )}

                {/* Model Configuration - 内部 Agent 默认展开 */}
                <CollapsibleSection title="Model Configuration" defaultOpen={isInternalAgent || !!modelProvider || !!modelName}>
                  <div className="grid grid-cols-2 gap-4">
                    {/* Provider */}
                    <div>
                      <label className="block text-xs text-fg-muted mb-1">Provider</label>
                      <select
                        value={modelProvider}
                        onChange={(e) => setModelProvider(e.target.value)}
                        className="w-full px-3 py-2 bg-surface-base border border-line rounded-lg text-sm focus:outline-none focus:border-primary-500"
                      >
                        <option value="">Default</option>
                        <option value="anthropic">Anthropic</option>
                        <option value="openai">OpenAI</option>
                        <option value="deepseek">DeepSeek</option>
                      </select>
                    </div>

                    {/* Model */}
                    <div>
                      <label className="block text-xs text-fg-muted mb-1">Model</label>
                      <input
                        type="text"
                        value={modelName}
                        onChange={(e) => setModelName(e.target.value)}
                        placeholder="claude-sonnet-4-20250514"
                        className="w-full px-3 py-2 bg-surface-base border border-line rounded-lg text-sm focus:outline-none focus:border-primary-500"
                      />
                    </div>

                    {/* Temperature */}
                    <div>
                      <label className="block text-xs text-fg-muted mb-1">Temperature</label>
                      <input
                        type="number"
                        value={temperature ?? ''}
                        onChange={(e) =>
                          setTemperature(e.target.value ? parseFloat(e.target.value) : undefined)
                        }
                        placeholder="0.7"
                        min="0"
                        max="1"
                        step="0.1"
                        className="w-full px-3 py-2 bg-surface-base border border-line rounded-lg text-sm focus:outline-none focus:border-primary-500"
                      />
                    </div>

                    {/* Max Tokens */}
                    <div>
                      <label className="block text-xs text-fg-muted mb-1">Max Tokens</label>
                      <input
                        type="number"
                        value={maxTokens ?? ''}
                        onChange={(e) =>
                          setMaxTokens(e.target.value ? parseInt(e.target.value) : undefined)
                        }
                        placeholder="8192"
                        min="1"
                        className="w-full px-3 py-2 bg-surface-base border border-line rounded-lg text-sm focus:outline-none focus:border-primary-500"
                      />
                    </div>
                  </div>
                </CollapsibleSection>

                {/* Tool Configuration - 不为内部 Agent 显示 */}
                {!isInternalAgent && (
                  <CollapsibleSection title="Tool Configuration" defaultOpen={toolMode !== 'all' || noTask}>
                    <div className="space-y-4">
                      {/* Tool Mode */}
                      <div>
                        <label className="block text-xs text-fg-muted mb-1">Tool Access</label>
                        <div className="flex gap-2">
                          {(['all', 'enabled', 'disabled'] as const).map((m) => (
                            <button
                              key={m}
                              type="button"
                              onClick={() => setToolMode(m)}
                              className={cn(
                                'px-3 py-2 rounded-lg text-sm transition-colors',
                                toolMode === m
                                  ? 'bg-primary-500 text-white'
                                  : 'bg-surface-base text-fg-muted hover:bg-surface-subtle'
                              )}
                            >
                              {m === 'all' ? 'All Tools' : m === 'enabled' ? 'Only These' : 'Except These'}
                            </button>
                          ))}
                        </div>
                      </div>

                      {/* Tool List */}
                      {toolMode !== 'all' && (
                        <div>
                          <label className="block text-xs text-fg-muted mb-1">
                            {toolMode === 'enabled' ? 'Enabled Tools' : 'Disabled Tools'}
                          </label>
                          <input
                            type="text"
                            value={toolList}
                            onChange={(e) => setToolList(e.target.value)}
                            placeholder="bash, read_file, write_file"
                            className="w-full px-3 py-2 bg-surface-base border border-line rounded-lg text-sm focus:outline-none focus:border-primary-500"
                          />
                          <p className="text-xs text-fg-subtle mt-1">Comma-separated tool names</p>
                        </div>
                      )}

                      {/* No Task */}
                      <div className="flex items-center gap-2">
                        <input
                          type="checkbox"
                          id="noTask"
                          checked={noTask}
                          onChange={(e) => setNoTask(e.target.checked)}
                          className="w-4 h-4 rounded border-line-muted bg-surface-base text-primary-500 focus:ring-primary-500"
                        />
                        <label htmlFor="noTask" className="text-sm text-fg-secondary">
                          Disable nested Task calls
                        </label>
                      </div>
                    </div>
                  </CollapsibleSection>
                )}

                {/* Execution Limits - 不为内部 Agent 显示 */}
                {!isInternalAgent && (
                  <CollapsibleSection title="Execution Limits" defaultOpen={maxSteps !== undefined}>
                    <div>
                      <label className="block text-xs text-fg-muted mb-1">Max Steps</label>
                      <input
                        type="number"
                        value={maxSteps ?? ''}
                        onChange={(e) =>
                          setMaxSteps(e.target.value ? parseInt(e.target.value) : undefined)
                        }
                        placeholder="15"
                        min="1"
                        className="w-full px-3 py-2 bg-surface-base border border-line rounded-lg text-sm focus:outline-none focus:border-primary-500"
                      />
                      <p className="text-xs text-fg-subtle mt-1">
                        Maximum number of tool call steps. Leave empty for default.
                      </p>
                    </div>
                  </CollapsibleSection>
                )}
              </>
            )}
          </div>

          {/* Footer */}
          <div
            className={cn(
              'border-t border-line flex justify-end gap-2',
              responsive ? 'px-4 py-3 safe-area-pb' : 'px-6 py-3'
            )}
          >
            <Button variant="ghost" onClick={onClose}>
              Cancel
            </Button>
            <Button variant="default" onClick={handleSave} disabled={saving || loading}>
              <Save size={16} className="mr-1" />
              {saving ? 'Saving...' : 'Save'}
            </Button>
          </div>
        </motion.div>
      </motion.div>
    </AnimatePresence>
  );
}
