/**
 * Agents 管理中心页面
 */
import { useState, useEffect } from 'react'
import {
  Card,
  Row,
  Col,
  Steps,
  Timeline,
  Button,
  Tag,
  Collapse,
  Space,
  Modal,
  Form,
  Input,
  Select,
  Drawer,
  message,
  Tabs,
  Badge,
  Divider,
  Tooltip,
  Popconfirm,
  Empty,
  Spin,
  Alert,
  List
} from 'antd'
import {
  PlayCircleOutlined,
  SettingOutlined,
  CheckCircleOutlined,
  PlusOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  CopyOutlined,
  CloseCircleOutlined,
  LoadingOutlined,
  ClockCircleOutlined,
  RocketOutlined,
  ApiOutlined,
  AppstoreOutlined,
  CopyToClipboard
} from '@ant-design/icons'

const { Panel } = Collapse
const { TabPane } = Tabs
const { Option } = Select
const { TextArea } = Input

// Agent types and interfaces
export interface AgentSkillBinding {
  stage: string
  skill_id: string
  skill_name: string
  configurable: boolean
  enabled: boolean
}

export interface AgentWorkflowStep {
  id: string
  title: string
  description: string
  skill_id?: string
  skill_name?: string
  status: 'pending' | 'running' | 'success' | 'error'
  result?: string
  error?: string
}

export interface Agent {
  id: string
  name: string
  description: string
  category: string
  type: 'builtin' | 'user'
  status: 'active' | 'inactive'
  workflow_steps: AgentWorkflowStep[]
  skill_bindings: AgentSkillBinding[]
  execution_rules: {
    quality_check: boolean
    quality_threshold: number
    max_retries: number
    auto_update_memory: boolean
  }
  config: Record<string, any>
  created_at?: string
  updated_at?: string
}

// Mock agents data (would come from API)
const mockAgents: Agent[] = [
  {
    id: 'series-creation',
    name: '剧集创作 Agent',
    description: '用于短剧和连续剧的自动创作，包含完整的 5 阶段工作流',
    category: '创作类',
    type: 'builtin',
    status: 'active',
    workflow_steps: [
      {
        id: '1',
        title: '加载全局上下文',
        description: '读取项目的世界观、人物小传、场景设定和历史记忆',
        status: 'pending'
      },
      {
        id: '2',
        title: '结构分析',
        description: '分析本集的场景构成、关键事件和转折点',
        skill_id: 'script-structure-analyzer',
        skill_name: '剧本结构分析器',
        status: 'pending'
      },
      {
        id: '3',
        title: '大纲生成',
        description: '生成本集的详细大纲，包含场景划分和情节走向',
        skill_id: 'outline-generator',
        skill_name: '大纲生成器',
        status: 'pending'
      },
      {
        id: '4',
        title: '对话创作',
        description: '使用 Skill 行为指导创作完整的剧本对话',
        skill_id: 'dialogue-writer-ancient',
        skill_name: '古风对话创作',
        status: 'pending'
      },
      {
        id: '5',
        title: '一致性审核',
        description: '检查内容与全局设定和历史剧情的一致性',
        skill_id: 'consistency-checker',
        skill_name: '一致性检查',
        status: 'pending'
      }
    ],
    skill_bindings: [
      { stage: '结构分析', skill_id: 'script-structure-analyzer', skill_name: '剧本结构分析器', configurable: true, enabled: true },
      { stage: '大纲生成', skill_id: 'outline-generator', skill_name: '大纲生成器', configurable: true, enabled: true },
      { stage: '对话创作', skill_id: 'dialogue-writer-ancient', skill_name: '古风对话创作', configurable: true, enabled: true },
      { stage: '一致性审核', skill_id: 'consistency-checker', skill_name: '一致性检查', configurable: true, enabled: true }
    ],
    execution_rules: {
      quality_check: true,
      quality_threshold: 85,
      max_retries: 3,
      auto_update_memory: true
    },
    config: {
      max_episodes: 100,
      language: 'zh-CN',
      style: 'ancient'
    }
  }
]

export const AgentManagement = () => {
  // State
  const [agents, setAgents] = useState<Agent[]>(mockAgents)
  const [selectedAgent, setSelectedAgent] = useState<Agent | null>(null)
  const [loading, setLoading] = useState(false)

  // Detail drawer state
  const [detailDrawerOpen, setDetailDrawerOpen] = useState(false)

  // Test modal state
  const [testModalOpen, setTestModalOpen] = useState(false)
  const [testInput, setTestInput] = useState('')
  const [testRunning, setTestRunning] = useState(false)
  const [testResults, setTestResults] = useState<AgentWorkflowStep[]>([])

  // Create/Edit modal state
  const [createModalOpen, setCreateModalOpen] = useState(false)
  const [editModalOpen, setEditModalOpen] = useState(false)
  const [editingAgent, setEditingAgent] = useState<Agent | null>(null)
  const [form] = Form.useForm()
  const [submitting, setSubmitting] = useState(false)

  // Config modal state
  const [configDrawerOpen, setConfigDrawerOpen] = useState(false)

  useEffect(() => {
    // In real app, fetch agents from API
    // fetchAgents()
  }, [])

  // Handlers
  const handleView = (agent: Agent) => {
    setSelectedAgent(agent)
    setDetailDrawerOpen(true)
  }

  const handleTest = (agent: Agent) => {
    setSelectedAgent(agent)
    setTestInput('')
    setTestResults([])
    setTestModalOpen(true)
  }

  const handleRunTest = async () => {
    if (!selectedAgent || !testInput.trim()) {
      message.warning('请输入测试内容')
      return
    }

    setTestRunning(true)
    setTestResults([])

    try {
      // Simulate running workflow
      const results: AgentWorkflowStep[] = []

      for (const step of selectedAgent.workflow_steps) {
        // Set running status
        setTestResults(prev => [
          ...prev,
          { ...step, status: 'running' }
        ])

        // Simulate delay
        await new Promise(resolve => setTimeout(resolve, 1500))

        // Set success status
        results.push({
          ...step,
          status: 'success',
          result: `[模拟结果] ${step.title} 已完成。\n输入: ${testInput}\n使用 Skill: ${step.skill_name || '无'}`
        })
        setTestResults([...results])
      }

      message.success('测试执行完成！')
    } catch (error) {
      message.error(`测试失败: ${(error as Error).message}`)
    } finally {
      setTestRunning(false)
    }
  }

  const handleCreate = () => {
    form.resetFields()
    setEditingAgent(null)
    form.setFieldsValue({
      execution_rules: {
        quality_check: true,
        quality_threshold: 85,
        max_retries: 3,
        auto_update_memory: true
      }
    })
    setCreateModalOpen(true)
  }

  const handleEdit = (agent: Agent) => {
    if (agent.type === 'builtin') {
      message.warning('内置 Agent 不允许编辑')
      return
    }
    setEditingAgent(agent)
    form.setFieldsValue({
      name: agent.name,
      description: agent.description,
      category: agent.category,
      execution_rules: agent.execution_rules,
      config: agent.config
    })
    setEditModalOpen(true)
  }

  const handleCopy = (agent: Agent) => {
    form.resetFields()
    setEditingAgent(null)
    form.setFieldsValue({
      id: `${agent.id}-copy-${Date.now()}`,
      name: `${agent.name} (副本)`,
      description: agent.description,
      category: agent.category,
      execution_rules: agent.execution_rules,
      config: agent.config
    })
    setCreateModalOpen(true)
    message.info('已复制 Agent 配置，请修改后保存')
  }

  const handleDelete = async (agent: Agent) => {
    if (agent.type === 'builtin') {
      message.warning('内置 Agent 不允许删除')
      return
    }

    try {
      // await agentService.deleteAgent(agent.id)
      setAgents(agents.filter(a => a.id !== agent.id))
      message.success('删除成功')
      if (selectedAgent?.id === agent.id) {
        setSelectedAgent(null)
        setDetailDrawerOpen(false)
      }
    } catch (error) {
      message.error(`删除失败: ${(error as Error).message}`)
    }
  }

  const handleCreateSubmit = async () => {
    try {
      const values = await form.validateFields()
      setSubmitting(true)

      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 1000))

      const newAgent: Agent = {
        id: values.id || `agent-${Date.now()}`,
        name: values.name,
        description: values.description,
        category: values.category,
        type: 'user',
        status: 'active',
        workflow_steps: [],
        skill_bindings: [],
        execution_rules: values.execution_rules || {},
        config: values.config || {},
        created_at: new Date().toISOString()
      }

      setAgents([...agents, newAgent])
      message.success('创建成功')
      setCreateModalOpen(false)
      form.resetFields()
    } catch (error) {
      message.error(`创建失败: ${(error as Error).message}`)
    } finally {
      setSubmitting(false)
    }
  }

  const handleEditSubmit = async () => {
    if (!editingAgent) return

    try {
      const values = await form.validateFields()
      setSubmitting(true)

      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 1000))

      const updatedAgent = {
        ...editingAgent,
        name: values.name,
        description: values.description,
        category: values.category,
        execution_rules: values.execution_rules,
        config: values.config,
        updated_at: new Date().toISOString()
      }

      setAgents(agents.map(a => a.id === editingAgent.id ? updatedAgent : a))
      setSelectedAgent(updatedAgent)
      message.success('更新成功')
      setEditModalOpen(false)
      setEditingAgent(null)
      form.resetFields()
    } catch (error) {
      message.error(`更新失败: ${(error as Error).message}`)
    } finally {
      setSubmitting(false)
    }
  }

  const handleViewConfig = (agent: Agent) => {
    setSelectedAgent(agent)
    setConfigDrawerOpen(true)
  }

  return (
    <div style={{ padding: '24px' }}>
      <Card
        title={
          <Space>
            <RocketOutlined />
            <span>Agents 管理中心</span>
          </Space>
        }
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
            创建 Agent
          </Button>
        }
      >
        <Row gutter={16}>
          {/* 左侧：Agent 列表 */}
          <Col span={8}>
            <Card
              title="Agents 列表"
              size="small"
              extra={
                <Space>
                  <Tag color="green">活跃: {agents.filter(a => a.status === 'active').length}</Tag>
                  <Tag>总计: {agents.length}</Tag>
                </Space>
              }
            >
              <Space direction="vertical" style={{ width: '100%' }} size="middle">
                {agents.map(agent => (
                  <Card
                    key={agent.id}
                    size="small"
                    hoverable
                    style={{
                      cursor: 'pointer',
                      border: selectedAgent?.id === agent.id ? '2px solid #1890ff' : undefined
                    }}
                    onClick={() => setSelectedAgent(agent)}
                  >
                    <Space direction="vertical" style={{ width: '100%' }} size="small">
                      <Space style={{ width: '100%', justifyContent: 'space-between' }}>
                        <Space>
                          <strong>{agent.name}</strong>
                          {agent.type === 'builtin' && (
                            <Badge count="系统" style={{ backgroundColor: '#1890ff' }} />
                          )}
                        </Space>
                        <Tag color={agent.status === 'active' ? 'green' : 'default'} size="small">
                          {agent.status === 'active' ? '活跃' : '未激活'}
                        </Tag>
                      </Space>
                      <p style={{ color: '#666', fontSize: '12px', margin: 0 }}>
                        {agent.description}
                      </p>
                      <Space size="small" wrap>
                        <Tag color="blue" style={{ fontSize: '11px' }}>{agent.category}</Tag>
                        <Tag style={{ fontSize: '11px' }}>{agent.workflow_steps.length} 个步骤</Tag>
                        <Tag style={{ fontSize: '11px' }}>{agent.skill_bindings.length} 个技能</Tag>
                      </Space>
                      <Divider style={{ margin: '8px 0' }} />
                      <Space size="small" onClick={(e) => e.stopPropagation()}>
                        <Tooltip title="查看详情">
                          <Button
                            type="link"
                            size="small"
                            icon={<EyeOutlined />}
                            onClick={() => handleView(agent)}
                          >
                            查看
                          </Button>
                        </Tooltip>
                        <Tooltip title="测试运行">
                          <Button
                            type="link"
                            size="small"
                            icon={<PlayCircleOutlined />}
                            onClick={() => handleTest(agent)}
                          >
                            测试
                          </Button>
                        </Tooltip>
                        <Tooltip title="查看配置">
                          <Button
                            type="link"
                            size="small"
                            icon={<SettingOutlined />}
                            onClick={() => handleViewConfig(agent)}
                          >
                            配置
                          </Button>
                        </Tooltip>
                        {agent.type === 'user' && (
                          <>
                            <Tooltip title="编辑">
                              <Button
                                type="link"
                                size="small"
                                icon={<EditOutlined />}
                                onClick={() => handleEdit(agent)}
                              >
                                编辑
                              </Button>
                            </Tooltip>
                            <Tooltip title="复制">
                              <Button
                                type="link"
                                size="small"
                                icon={<CopyOutlined />}
                                onClick={() => handleCopy(agent)}
                              >
                                复制
                              </Button>
                            </Tooltip>
                            <Popconfirm
                              title="确认删除"
                              description="确定要删除这个 Agent 吗？"
                              onConfirm={() => handleDelete(agent)}
                              okText="确认"
                              cancelText="取消"
                            >
                              <Tooltip title="删除">
                                <Button
                                  type="link"
                                  size="small"
                                  danger
                                  icon={<DeleteOutlined />}
                                >
                                  删除
                                </Button>
                              </Tooltip>
                            </Popconfirm>
                          </>
                        )}
                        {agent.type === 'builtin' && (
                          <Tooltip title="复制内置 Agent">
                            <Button
                              type="link"
                              size="small"
                              icon={<CopyOutlined />}
                              onClick={() => handleCopy(agent)}
                            >
                              复制
                            </Button>
                          </Tooltip>
                        )}
                      </Space>
                    </Space>
                  </Card>
                ))}
              </Space>
            </Card>
          </Col>

          {/* 右侧：Agent 详情 */}
          <Col span={16}>
            {selectedAgent ? (
              <Card
                title={
                  <Space>
                    <span>{selectedAgent.name} 详情</span>
                    {selectedAgent.type === 'builtin' && (
                      <Badge count="系统" style={{ backgroundColor: '#1890ff' }} />
                    )}
                  </Space>
                }
                extra={
                  <Space>
                    <Button
                      icon={<EyeOutlined />}
                      onClick={() => handleView(selectedAgent)}
                    >
                      完整详情
                    </Button>
                    <Button
                      icon={<PlayCircleOutlined />}
                      onClick={() => handleTest(selectedAgent)}
                    >
                      测试运行
                    </Button>
                    <Button
                      icon={<SettingOutlined />}
                      onClick={() => handleViewConfig(selectedAgent)}
                    >
                      配置
                    </Button>
                  </Space>
                }
              >
                <Tabs defaultActiveKey="overview">
                  <TabPane tab="概览" key="overview">
                    <Space direction="vertical" style={{ width: '100%' }} size="large">
                      {/* 基本信息 */}
                      <Card size="small" title="基本信息">
                        <Space direction="vertical" style={{ width: '100%' }} size="small">
                          <div><strong>名称:</strong> {selectedAgent.name}</div>
                          <div><strong>分类:</strong> <Tag color="blue">{selectedAgent.category}</Tag></div>
                          <div><strong>状态:</strong>
                            <Tag color={selectedAgent.status === 'active' ? 'green' : 'default'}>
                              {selectedAgent.status === 'active' ? '活跃' : '未激活'}
                            </Tag>
                          </div>
                          <div><strong>类型:</strong>
                            <Tag
                              color={selectedAgent.type === 'builtin' ? 'blue' : 'green'}
                              icon={selectedAgent.type === 'builtin' ? <ApiOutlined /> : undefined}
                            >
                              {selectedAgent.type === 'builtin' ? '内置 Agent' : '用户 Agent'}
                            </Tag>
                          </div>
                          <div><strong>描述:</strong> {selectedAgent.description}</div>
                          {selectedAgent.created_at && (
                            <div><strong>创建时间:</strong> {selectedAgent.created_at}</div>
                          )}
                        </Space>
                      </Card>

                      {/* 工作流概览 */}
                      <Card size="small" title="工作流步骤">
                        <Timeline
                          items={selectedAgent.workflow_steps.map((step, idx) => ({
                            color: step.status === 'running' ? 'blue' : 'gray',
                            dot: step.status === 'running' ? <LoadingOutlined /> : <ClockCircleOutlined />,
                            children: (
                              <div>
                                <p><strong>{step.title}</strong></p>
                                <p style={{ color: '#666', fontSize: '12px' }}>{step.description}</p>
                                {step.skill_name && (
                                  <Tag color="blue" style={{ fontSize: '11px' }}>
                                    <AppstoreOutlined style={{ marginRight: '4px' }} />
                                    {step.skill_name}
                                  </Tag>
                                )}
                              </div>
                            )
                          }))}
                        />
                      </Card>

                      {/* 绑定的 Skills */}
                      <Card size="small" title="绑定的 Skills">
                        <List
                          size="small"
                          dataSource={selectedAgent.skill_bindings}
                          renderItem={binding => (
                            <List.Item>
                              <Space style={{ width: '100%', justifyContent: 'space-between' }}>
                                <Space>
                                  <strong>{binding.stage}</strong>
                                  <Tag color="blue">{binding.skill_name}</Tag>
                                  {binding.configurable && (
                                    <Tag color="orange" size="small">可配置</Tag>
                                  )}
                                </Space>
                                <Tag color={binding.enabled ? 'green' : 'default'} size="small">
                                  {binding.enabled ? '已启用' : '已禁用'}
                                </Tag>
                              </Space>
                            </List.Item>
                          )}
                        />
                      </Card>
                    </Space>
                  </TabPane>

                  <TabPane tab="工作流" key="workflow">
                    <Space direction="vertical" style={{ width: '100%' }} size="middle">
                      <Steps
                        direction="vertical"
                        current={-1}
                        items={selectedAgent.workflow_steps.map(step => ({
                          title: step.title,
                          description: (
                            <div>
                              <p>{step.description}</p>
                              {step.skill_name && (
                                <Tag color="blue">
                                  <AppstoreOutlined style={{ marginRight: '4px' }} />
                                  Skill: {step.skill_name}
                                </Tag>
                              )}
                            </div>
                          ),
                          status: 'wait',
                          icon: <ClockCircleOutlined />
                        }))}
                      />
                    </Space>
                  </TabPane>

                  <TabPane tab="执行规则" key="rules">
                    <Card size="small">
                      <Collapse
                        items={[
                          {
                            key: '1',
                            label: '质量检测',
                            children: (
                              <Space direction="vertical" size="small">
                                <div>
                                  <strong>启用质量检测:</strong>{' '}
                                  <Tag color={selectedAgent.execution_rules.quality_check ? 'green' : 'default'}>
                                    {selectedAgent.execution_rules.quality_check ? '是' : '否'}
                                  </Tag>
                                </div>
                                <div>
                                  <strong>质量阈值:</strong> {selectedAgent.execution_rules.quality_threshold} 分
                                </div>
                                <div>
                                  <strong>最大重试次数:</strong> {selectedAgent.execution_rules.max_retries} 次
                                </div>
                                <p style={{ color: '#999', fontSize: '12px' }}>
                                  质量分数低于阈值时自动重试，连续重试失败则标记为"需人工审核"
                                </p>
                              </Space>
                            )
                          },
                          {
                            key: '2',
                            label: '记忆管理',
                            children: (
                              <Space direction="vertical" size="small">
                                <div>
                                  <strong>自动更新记忆:</strong>{' '}
                                  <Tag color={selectedAgent.execution_rules.auto_update_memory ? 'green' : 'default'}>
                                    {selectedAgent.execution_rules.auto_update_memory ? '是' : '否'}
                                  </Tag>
                                </div>
                                <ul style={{ color: '#666', fontSize: '13px' }}>
                                  <li>每集完成后自动提取关键事件</li>
                                  <li>检测新伏笔并记录</li>
                                  <li>追踪人物状态变化</li>
                                </ul>
                              </Space>
                            )
                          }
                        ]}
                      />
                    </Card>
                  </TabPane>

                  <TabPane tab="快速操作" key="actions">
                    <Space direction="vertical" style={{ width: '100%' }} size="large">
                      <Alert
                        message="操作提示"
                        description="选择下面的操作来管理当前 Agent"
                        type="info"
                        showIcon
                      />
                      <Card size="small" title="测试与运行">
                        <Space direction="vertical" style={{ width: '100%' }}>
                          <Button
                            type="primary"
                            size="large"
                            icon={<PlayCircleOutlined />}
                            onClick={() => handleTest(selectedAgent)}
                            block
                          >
                            测试运行 Agent
                          </Button>
                          <p style={{ color: '#999', fontSize: '12px' }}>
                            使用测试输入运行完整工作流，查看每个步骤的执行结果
                          </p>
                        </Space>
                      </Card>
                      <Card size="small" title="配置管理">
                        <Space direction="vertical" style={{ width: '100%' }}>
                          <Button
                            icon={<SettingOutlined />}
                            onClick={() => handleViewConfig(selectedAgent)}
                            block
                          >
                            查看完整配置
                          </Button>
                          {selectedAgent.type === 'user' && (
                            <Button
                              icon={<EditOutlined />}
                              onClick={() => handleEdit(selectedAgent)}
                              block
                            >
                              编辑 Agent
                            </Button>
                          )}
                        </Space>
                      </Card>
                    </Space>
                  </TabPane>
                </Tabs>
              </Card>
            ) : (
              <Card>
                <Empty
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                  description="请从左侧选择一个 Agent 查看详情"
                />
              </Card>
            )}
          </Col>
        </Row>
      </Card>

      {/* Agent 详情抽屉 */}
      <Drawer
        title={
          <Space>
            <EyeOutlined />
            <span>{selectedAgent?.name} - 完整详情</span>
          </Space>
        }
        placement="right"
        width={800}
        open={detailDrawerOpen}
        onClose={() => setDetailDrawerOpen(false)}
      >
        {selectedAgent && (
          <Tabs defaultActiveKey="info">
            <TabPane tab="基本信息" key="info">
              <Space direction="vertical" style={{ width: '100%' }} size="middle">
                <Card size="small">
                  <pre style={{
                    background: '#f5f5f5',
                    padding: '16px',
                    borderRadius: '4px',
                    overflow: 'auto'
                  }}>
                    {JSON.stringify(selectedAgent, null, 2)}
                  </pre>
                </Card>
              </Space>
            </TabPane>
          </Tabs>
        )}
      </Drawer>

      {/* Agent 测试弹窗 */}
      <Modal
        title={
          <Space>
            <PlayCircleOutlined />
            <span>测试 Agent: {selectedAgent?.name}</span>
          </Space>
        }
        open={testModalOpen}
        onCancel={() => {
          setTestModalOpen(false)
          setTestInput('')
          setTestResults([])
        }}
        width={900}
        footer={null}
        destroyOnClose
      >
        {selectedAgent && (
          <Space direction="vertical" style={{ width: '100%' }} size="large">
            <div>
              <div style={{ marginBottom: '8px' }}>
                <strong>测试输入:</strong>
                <span style={{ color: '#999', marginLeft: '8px', fontSize: '12px' }}>
                  输入要发送给 Agent 的任务描述
                </span>
              </div>
              <TextArea
                rows={4}
                placeholder="输入测试内容... 例如：创作一集关于宫廷斗争的剧集"
                value={testInput}
                onChange={(e) => setTestInput(e.target.value)}
                disabled={testRunning}
              />
            </div>

            <Button
              type="primary"
              size="large"
              loading={testRunning}
              onClick={handleRunTest}
              disabled={!testInput.trim() || testRunning}
              block
              icon={<PlayCircleOutlined />}
            >
              {testRunning ? '执行中...' : '开始测试'}
            </Button>

            {testResults.length > 0 && (
              <Card
                title={
                  <Space>
                    <CheckCircleOutlined style={{ color: '#52c41a' }} />
                    <span>执行结果</span>
                  </Space>
                }
                size="small"
              >
                <Timeline
                  items={testResults.map(step => ({
                    color: step.status === 'success' ? 'green' : step.status === 'error' ? 'red' : 'blue',
                    dot: step.status === 'success' ? <CheckCircleOutlined /> :
                         step.status === 'error' ? <CloseCircleOutlined /> :
                         <LoadingOutlined />,
                    children: (
                      <div>
                        <p><strong>{step.title}</strong></p>
                        {step.result && (
                          <Card size="small" style={{ marginTop: '8px', background: '#f5f5f5' }}>
                            <pre style={{
                              whiteSpace: 'pre-wrap',
                              fontSize: '12px',
                              margin: 0
                            }}>
                              {step.result}
                            </pre>
                          </Card>
                        )}
                        {step.error && (
                          <Alert
                            type="error"
                            message={step.error}
                            size="small"
                            style={{ marginTop: '8px' }}
                          />
                        )}
                      </div>
                    )
                  }))}
                />
              </Card>
            )}

            {!testRunning && testResults.length === 0 && (
              <Card size="small" style={{ background: '#fafafa' }}>
                <Space direction="vertical" size="small">
                  <p style={{ margin: 0, color: '#666' }}>
                    <strong>提示:</strong> 输入测试内容后点击"开始测试"按钮
                  </p>
                  <p style={{ margin: 0, color: '#999', fontSize: '12px' }}>
                    Agent 将按照工作流步骤顺序执行，每个步骤都会使用对应的 Skill
                  </p>
                </Space>
              </Card>
            )}
          </Space>
        )}
      </Modal>

      {/* 创建 Agent 弹窗 */}
      <Modal
        title={
          <Space>
            <PlusOutlined />
            <span>创建新 Agent</span>
          </Space>
        }
        open={createModalOpen}
        onCancel={() => {
          setCreateModalOpen(false)
          form.resetFields()
        }}
        width={700}
        footer={[
          <Button key="cancel" onClick={() => setCreateModalOpen(false)}>
            取消
          </Button>,
          <Button
            key="submit"
            type="primary"
            loading={submitting}
            onClick={handleCreateSubmit}
          >
            创建
          </Button>
        ]}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            execution_rules: {
              quality_check: true,
              quality_threshold: 85,
              max_retries: 3,
              auto_update_memory: true
            }
          }}
        >
          <Form.Item
            label="Agent ID"
            name="id"
            rules={[
              { required: true, message: '请输入 Agent ID' },
              { pattern: /^[a-z0-9-]+$/, message: '只能包含小写字母、数字和连字符' }
            ]}
          >
            <Input placeholder="例如: my-custom-agent" prefix={<RocketOutlined />} />
          </Form.Item>

          <Form.Item
            label="Agent 名称"
            name="name"
            rules={[{ required: true, message: '请输入 Agent 名称' }]}
          >
            <Input placeholder="例如: 自定义创作助手" />
          </Form.Item>

          <Form.Item
            label="分类"
            name="category"
            rules={[{ required: true, message: '请选择分类' }]}
          >
            <Select placeholder="选择分类">
              <Option value="创作类">创作类</Option>
              <Option value="分析类">分析类</Option>
              <Option value="管理类">管理类</Option>
              <Option value="工具类">工具类</Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="描述"
            name="description"
            rules={[{ required: true, message: '请输入描述' }]}
          >
            <TextArea rows={3} placeholder="输入 Agent 的功能描述..." />
          </Form.Item>

          <Card size="small" title="执行规则" style={{ marginBottom: '16px' }}>
            <Form.Item
              label="质量检测"
              name={['execution_rules', 'quality_check']}
              valuePropName="checked"
            >
              <Select>
                <Option value={true}>启用</Option>
                <Option value={false}>禁用</Option>
              </Select>
            </Form.Item>
            <Form.Item
              label="质量阈值"
              name={['execution_rules', 'quality_threshold']}
            >
              <Input type="number" placeholder="85" />
            </Form.Item>
            <Form.Item
              label="最大重试次数"
              name={['execution_rules', 'max_retries']}
            >
              <Input type="number" placeholder="3" />
            </Form.Item>
            <Form.Item
              label="自动更新记忆"
              name={['execution_rules', 'auto_update_memory']}
              valuePropName="checked"
            >
              <Select>
                <Option value={true}>启用</Option>
                <Option value={false}>禁用</Option>
              </Select>
            </Form.Item>
          </Card>
        </Form>
      </Modal>

      {/* 编辑 Agent 弹窗 */}
      <Modal
        title={
          <Space>
            <EditOutlined />
            <span>编辑 Agent: {editingAgent?.name}</span>
          </Space>
        }
        open={editModalOpen}
        onCancel={() => {
          setEditModalOpen(false)
          setEditingAgent(null)
          form.resetFields()
        }}
        width={700}
        footer={[
          <Button key="cancel" onClick={() => setEditModalOpen(false)}>
            取消
          </Button>,
          <Button
            key="submit"
            type="primary"
            loading={submitting}
            onClick={handleEditSubmit}
          >
            保存
          </Button>
        ]}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Form.Item
            label="Agent 名称"
            name="name"
            rules={[{ required: true, message: '请输入 Agent 名称' }]}
          >
            <Input placeholder="例如: 自定义创作助手" />
          </Form.Item>

          <Form.Item
            label="分类"
            name="category"
            rules={[{ required: true, message: '请选择分类' }]}
          >
            <Select placeholder="选择分类">
              <Option value="创作类">创作类</Option>
              <Option value="分析类">分析类</Option>
              <Option value="管理类">管理类</Option>
              <Option value="工具类">工具类</Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="描述"
            name="description"
            rules={[{ required: true, message: '请输入描述' }]}
          >
            <TextArea rows={3} placeholder="输入 Agent 的功能描述..." />
          </Form.Item>

          <Card size="small" title="执行规则" style={{ marginBottom: '16px' }}>
            <Form.Item
              label="质量检测"
              name={['execution_rules', 'quality_check']}
              valuePropName="checked"
            >
              <Select>
                <Option value={true}>启用</Option>
                <Option value={false}>禁用</Option>
              </Select>
            </Form.Item>
            <Form.Item
              label="质量阈值"
              name={['execution_rules', 'quality_threshold']}
            >
              <Input type="number" placeholder="85" />
            </Form.Item>
            <Form.Item
              label="最大重试次数"
              name={['execution_rules', 'max_retries']}
            >
              <Input type="number" placeholder="3" />
            </Form.Item>
            <Form.Item
              label="自动更新记忆"
              name={['execution_rules', 'auto_update_memory']}
              valuePropName="checked"
            >
              <Select>
                <Option value={true}>启用</Option>
                <Option value={false}>禁用</Option>
              </Select>
            </Form.Item>
          </Card>
        </Form>
      </Modal>

      {/* 配置查看抽屉 */}
      <Drawer
        title={
          <Space>
            <SettingOutlined />
            <span>{selectedAgent?.name} - 完整配置</span>
          </Space>
        }
        placement="right"
        width={600}
        open={configDrawerOpen}
        onClose={() => setConfigDrawerOpen(false)}
      >
        {selectedAgent && (
          <Space direction="vertical" style={{ width: '100%' }} size="large">
            <Card size="small" title="Agent 配置 (JSON)">
              <pre style={{
                background: '#f5f5f5',
                padding: '16px',
                borderRadius: '4px',
                maxHeight: '65vh',
                overflowY: 'auto',
                fontSize: '12px',
                wordBreak: 'break-word',
                lineHeight: '1.5'
              }}>
                {JSON.stringify(selectedAgent, null, 2)}
              </pre>
              <Button
                block
                icon={<CopyOutlined />}
                onClick={() => {
                  navigator.clipboard.writeText(JSON.stringify(selectedAgent, null, 2))
                  message.success('已复制到剪贴板')
                }}
                style={{ marginTop: '8px' }}
              >
                复制配置
              </Button>
            </Card>

            <Card size="small" title="执行规则">
              <Space direction="vertical" style={{ width: '100%' }} size="small">
                <div>
                  <strong>质量检测:</strong>{' '}
                  <Tag color={selectedAgent.execution_rules.quality_check ? 'green' : 'default'}>
                    {selectedAgent.execution_rules.quality_check ? '启用' : '禁用'}
                  </Tag>
                </div>
                <div>
                  <strong>质量阈值:</strong> {selectedAgent.execution_rules.quality_threshold}
                </div>
                <div>
                  <strong>最大重试:</strong> {selectedAgent.execution_rules.max_retries}
                </div>
                <div>
                  <strong>自动更新记忆:</strong>{' '}
                  <Tag color={selectedAgent.execution_rules.auto_update_memory ? 'green' : 'default'}>
                    {selectedAgent.execution_rules.auto_update_memory ? '启用' : '禁用'}
                  </Tag>
                </div>
              </Space>
            </Card>

            <Card size="small" title="其他配置">
              <pre style={{
                background: '#f5f5f5',
                padding: '16px',
                borderRadius: '4px',
                maxHeight: '300px',
                overflow: 'auto'
              }}>
                {JSON.stringify(selectedAgent.config || {}, null, 2)}
              </pre>
            </Card>
          </Space>
        )}
      </Drawer>
    </div>
  )
}
