/**
 * Review Configuration Page
 *
 * 审核配置页面
 *
 * 功能：
 * 1. 配置摘要 - 查看当前配置概览
 * 2. 审核Skills - 跳转到Skills管理页面创建/管理审核Skills
 * 3. 自定义规则 - 配置自定义审核规则
 * 4. Agent指令 - 自动整合所有配置的Agent指令预览
 */
import React, { useEffect, useState, useMemo } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import {
  Card,
  Form,
  Button,
  Space,
  Select,
  Input,
  Modal,
  Tag,
  Row,
  Col,
  Alert,
  message,
  Tabs,
  Typography,
  Progress,
  Spin,
  Empty,
  Slider,
  Switch,
  Divider
} from 'antd'
import {
  PlusOutlined,
  PlusCircleOutlined,
  SaveOutlined,
  DeleteOutlined,
  EditOutlined,
  InfoCircleOutlined,
  SettingOutlined,
  ReloadOutlined,
  FileTextOutlined,
  BulbOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  WarningOutlined
} from '@ant-design/icons'
import { useReviewStore } from '@/stores/reviewStore'
import type { ReviewRule } from '@/services/reviewService'
import { reviewService } from '@/services/reviewService'
import api from '@/services/api'

const { TabPane } = Tabs
const { Title, Text, Paragraph } = Typography

interface ReviewConfigProps {
  projectId?: string
}

interface ReviewSkill {
  id: string
  name: string
  description?: string
  category?: string
  enabled: boolean
}

// 规则分类映射
const categoryOptions = [
  { value: 'character', label: '角色', icon: '👤', color: 'blue' },
  { value: 'plot', label: '剧情', icon: '📖', color: 'purple' },
  { value: 'dialogue', label: '对话', icon: '💬', color: 'green' },
  { value: 'pacing', label: '节奏', icon: '⏱️', color: 'orange' },
  { value: 'emotion', label: '情感', icon: '❤️', color: 'pink' },
  { value: 'theme', label: '主题', icon: '🎯', color: 'cyan' },
  { value: 'other', label: '其他', icon: '📋', color: 'default' }
]

// 严重度配置
const severityConfig = {
  high: { label: '严重', color: '#ff4d4f', bgColor: '#fff1f0', icon: <CloseCircleOutlined /> },
  medium: { label: '普通', color: '#fa8c16', bgColor: '#fff7e6', icon: <WarningOutlined /> },
  low: { label: '轻微', color: '#52c41a', bgColor: '#f6ffed', icon: <InfoCircleOutlined /> }
}

const ReviewConfigPage: React.FC<ReviewConfigProps> = ({ projectId: propProjectId }) => {
  const { id: routeProjectId } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const projectId = propProjectId || routeProjectId

  const [form] = Form.useForm()
  const [configForm] = Form.useForm()
  const [activeTab, setActiveTab] = useState('overview')
  const [ruleModalVisible, setRuleModalVisible] = useState(false)
  const [editingRule, setEditingRule] = useState<ReviewRule | null>(null)
  const [configModalVisible, setConfigModalVisible] = useState(false)

  // 配置数据
  const [fullConfig, setFullConfig] = useState<any>(null)
  const [customRules, setCustomRules] = useState<ReviewRule[]>([])
  const [reviewSkills, setReviewSkills] = useState<ReviewSkill[]>([])
  const [skillsSearchText, setSkillsSearchText] = useState('')

  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (projectId) {
      loadConfiguration()
      loadCustomRules()
      loadReviewSkills()
    }
  }, [projectId])

  // 自动生成Agent指令预览
  const agentPromptPreview = useMemo(() => {
    if (!fullConfig && customRules.length === 0 && reviewSkills.length === 0) {
      return ''
    }

    let prompt = '# 审核配置指令\n\n'

    // 基本信息
    if (fullConfig) {
      prompt += `## 审核模式\n`
      prompt += `- 预设模式: ${fullConfig.preset === 'strict' ? '严格' : fullConfig.preset === 'standard' ? '标准' : fullConfig.preset === 'draft' ? '草稿' : '自定义'}\n`
      prompt += `- 通过阈值: ${fullConfig.pass_threshold || 75}分\n`
      prompt += `- 整体严格度: ${fullConfig.overall_strictness || 70}%\n\n`
    }

    // 维度配置
    if (fullConfig?.dimensions) {
      prompt += `## 审核维度\n`
      Object.entries(fullConfig.dimensions).forEach(([, dim]: [string, any]) => {
        if (dim.enabled) {
          prompt += `- ${dim.name}: 严格度 ${dim.strictness}%, 权重 ${(dim.weight * 100).toFixed(0)}%\n`
        }
      })
      prompt += '\n'
    }

    // 审核Skills
    if (reviewSkills.length > 0) {
      prompt += `## 审核Skills\n`
      reviewSkills.filter(s => s.enabled).forEach(skill => {
        prompt += `- ${skill.name}: ${skill.description || '无描述'}\n`
      })
      prompt += '\n'
    }

    // 自定义规则
    if (customRules.length > 0) {
      prompt += `## 自定义审核规则\n\n`
      customRules.forEach((rule, index) => {
        const categoryInfo = categoryOptions.find(c => c.value === (rule.category || rule.dimension || 'other')) || categoryOptions[6]
        prompt += `### 规则 ${index + 1}: ${rule.name}\n`
        prompt += `- **分类**: ${categoryInfo.label}\n`
        prompt += `- **严重度**: ${severityConfig[rule.severity as keyof typeof severityConfig]?.label || '普通'}\n`
        prompt += `- **描述**: ${rule.description}\n`
        prompt += `- **触发条件**: ${rule.triggerCondition}\n\n`
      })
    }

    prompt += `## 审核执行要求\n`
    prompt += `1. 根据上述配置对内容进行审核\n`
    prompt += `2. 按照严重度分类标记问题\n`
    prompt += `3. 计算总分并判断是否达到通过阈值\n`
    prompt += `4. 提供具体的改进建议\n`

    return prompt
  }, [fullConfig, customRules, reviewSkills])

  const loadConfiguration = async () => {
    if (!projectId) return
    try {
      const config = await reviewService.getConfiguration(projectId)
      setFullConfig(config)
    } catch (error) {
      console.error('Failed to load review config:', error)
    }
  }

  const loadCustomRules = async () => {
    if (!projectId) return
    try {
      const rules = await reviewService.getRules(projectId)
      setCustomRules(rules)
    } catch (error) {
      console.error('Failed to load custom rules:', error)
    }
  }

  const loadReviewSkills = async () => {
    if (!projectId) return
    try {
      const response = await api.get(`/projects/${projectId}/review/skills`)
      console.log('Review skills response:', response)
      const skills = (response as any)?.skills || []
      console.log('Parsed skills:', skills)
      console.log('Skills count:', skills.length)
      setReviewSkills(skills)
    } catch (error) {
      console.error('Failed to load review skills:', error)
    }
  }

  const handleCreateRule = async (values: any) => {
    if (!projectId) return
    try {
      const ruleData = {
        name: values.ruleName,
        description: values.ruleDescription,
        trigger_condition: values.triggerCondition,
        severity: values.severity,
        dimension: values.category
      }
      await reviewService.createRule(projectId, ruleData)
      message.success('规则创建成功')
      setRuleModalVisible(false)
      setEditingRule(null)
      form.resetFields()
      loadCustomRules()
    } catch (error) {
      console.error('Create rule error:', error)
      const errorMsg = (error as any)?.response?.data?.detail ||
                       (error as any)?.message ||
                       '规则创建失败'
      message.error(`规则创建失败: ${errorMsg}`)
    }
  }

  const handleUpdateRule = async (ruleId: string, values: any) => {
    if (!projectId) return
    try {
      const ruleData = {
        name: values.ruleName,
        description: values.ruleDescription,
        trigger_condition: values.triggerCondition,
        severity: values.severity,
        dimension: values.category
      }
      await reviewService.updateRule(projectId, ruleId, ruleData)
      message.success('规则更新成功')
      setRuleModalVisible(false)
      setEditingRule(null)
      form.resetFields()
      loadCustomRules()
    } catch (error) {
      console.error('Update rule error:', error)
      const errorMsg = (error as any)?.response?.data?.detail ||
                       (error as any)?.message ||
                       '规则更新失败'
      message.error(`规则更新失败: ${errorMsg}`)
    }
  }

  const handleDeleteRule = async (ruleId: string) => {
    if (!projectId) return
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条规则吗？',
      onOk: async () => {
        try {
          await api.delete(`/custom-rules/${ruleId}`, { params: { project_id: projectId } })
          message.success('规则删除成功')
          loadCustomRules()
        } catch (error) {
          console.error('Delete rule error:', error)
          const errorMsg = (error as any)?.message || '规则删除失败'
          message.error(`规则删除失败: ${errorMsg}`)
        }
      }
    })
  }

  const handleToggleSkill = async (skillId: string, enabled: boolean) => {
    try {
      await api.put(`/projects/${projectId}/review/skills/${skillId}`, { enabled })
      setReviewSkills(reviewSkills.map(s =>
        s.id === skillId ? { ...s, enabled } : s
      ))
      message.success('Skill状态更新成功')
    } catch (error) {
      message.error('Skill状态更新失败')
    }
  }

  // 刷新所有数据
  const handleRefreshAll = async () => {
    setLoading(true)
    try {
      await Promise.all([
        loadConfiguration(),
        loadCustomRules(),
        loadReviewSkills()
      ])
      message.success('刷新成功')
    } catch (error) {
      message.error('刷新失败')
    } finally {
      setLoading(false)
    }
  }

  // 打开配置编辑模态框
  const handleOpenConfigEdit = () => {
    if (fullConfig) {
      configForm.setFieldsValue({
        preset: fullConfig.preset || 'standard',
        pass_threshold: fullConfig.pass_threshold || 75,
        overall_strictness: fullConfig.overall_strictness || 70,
        dimensions: fullConfig.dimensions || {}
      })
    }
    setConfigModalVisible(true)
  }

  // 保存配置
  const handleSaveConfig = async (values: any) => {
    if (!projectId) return
    setLoading(true)
    try {
      const updateData: any = {
        preset: values.preset,
        pass_threshold: values.pass_threshold,
        overall_strictness: values.overall_strictness
      }

      // 更新维度配置
      if (values.dimensions) {
        updateData.dimensions = values.dimensions
      }

      await reviewService.updateConfiguration(projectId, updateData)
      message.success('配置保存成功')
      setConfigModalVisible(false)
      loadConfiguration()
    } catch (error) {
      console.error('Save config error:', error)
      message.error('配置保存失败: ' + (error as any)?.message || '')
    } finally {
      setLoading(false)
    }
  }

  // 渲染配置摘要
  const renderConfigSummary = () => {
    if (!fullConfig && customRules.length === 0) {
      return (
        <div style={{ textAlign: 'center', padding: '80px 0' }}>
          <SettingOutlined style={{ fontSize: 64, color: '#d9d9d9', marginBottom: 24 }} />
          <div>
            <Title level={4} type="secondary">暂无审核配置</Title>
            <Text type="secondary">请在其他标签页配置审核Skills和自定义规则</Text>
          </div>
        </div>
      )
    }

    const {
      preset = 'custom',
      dimensions = {},
      pass_threshold = 75
    } = fullConfig || {}

    // 计算维度统计
    const dimensionList = Object.values(dimensions || {})
    const totalDimensionsCount = dimensionList.length
    const enabledDimensionsCount = dimensionList.filter((d: any) => d.enabled).length

    // 统计规则
    const ruleStats = customRules.reduce((acc, rule) => {
      const severity = rule.severity || 'medium'
      acc[severity] = (acc[severity] || 0) + 1
      acc.total++
      return acc
    }, { high: 0, medium: 0, low: 0, total: 0 })

    const enabledSkillsCount = reviewSkills.filter(s => s.enabled).length

    return (
      <div style={{ maxWidth: 1000, margin: '0 auto', paddingBottom: '40px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 24 }}>
          <Title level={4} style={{ margin: 0 }}>当前配置摘要</Title>
          <Space>
            <Button
              icon={<EditOutlined />}
              onClick={handleOpenConfigEdit}
            >
              编辑配置
            </Button>
            <Button
              icon={<ReloadOutlined />}
              onClick={handleRefreshAll}
              loading={loading}
            >
              刷新
            </Button>
          </Space>
        </div>

        <Space direction="vertical" style={{ width: '100%' }} size="middle">
          {/* 快速概览 */}
          <Row gutter={16}>
            <Col span={6}>
              <Card className="summary-card">
                <div className="summary-value">
                  {preset === 'strict' ? '严格' : preset === 'standard' ? '标准' : preset === 'draft' ? '草稿' : '自定义'}
                </div>
                <div className="summary-label">审核模式</div>
              </Card>
            </Col>
            <Col span={6}>
              <Card className="summary-card">
                <div className="summary-value">{enabledSkillsCount}</div>
                <div className="summary-label">审核Skills</div>
              </Card>
            </Col>
            <Col span={6}>
              <Card className="summary-card">
                <div className="summary-value">{ruleStats.total}</div>
                <div className="summary-label">自定义规则</div>
              </Card>
            </Col>
            <Col span={6}>
              <Card className="summary-card">
                <div className="summary-value">{pass_threshold}分</div>
                <div className="summary-label">通过阈值</div>
              </Card>
            </Col>
          </Row>

          {/* 维度配置 */}
          {Object.keys(dimensions).length > 0 && (
            <Card title={<><FileTextOutlined /> 维度配置 ({enabledDimensionsCount}/{totalDimensionsCount})</>} size="small">
              <Row gutter={[12, 12]}>
                {Object.entries(dimensions).map(([key, dim]: [string, any]) => (
                  <Col span={8} key={key}>
                    <Card
                      size="small"
                      style={{
                        background: dim.enabled ? '#f0f9ff' : '#f5f5f5',
                        border: dim.enabled ? '1px solid #91d5ff' : '1px solid #d9d9d9'
                      }}
                    >
                      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                        <Text strong style={{ opacity: dim.enabled ? 1 : 0.5 }}>{dim.name}</Text>
                        <Tag color={dim.enabled ? 'success' : 'default'} style={{ margin: 0 }}>
                          {dim.enabled ? '启用' : '禁用'}
                        </Tag>
                      </div>
                      <Progress
                        percent={dim.strictness}
                        size="small"
                        strokeColor={dim.strictness >= 70 ? '#ff4d4f' : dim.strictness >= 50 ? '#faad14' : '#52c41a'}
                        showInfo={false}
                      />
                      <Text type="secondary" style={{ fontSize: 11 }}>权重: {(dim.weight * 100).toFixed(0)}%</Text>
                    </Card>
                  </Col>
                ))}
              </Row>
            </Card>
          )}

          {/* 规则统计 */}
          {ruleStats.total > 0 && (
            <Card title={<><BulbOutlined /> 规则统计</>} size="small">
              <Row gutter={16}>
                <Col span={6}>
                  <div className="stat-item">
                    <div className="stat-value">{ruleStats.total}</div>
                    <div className="stat-label">总规则</div>
                  </div>
                </Col>
                <Col span={6}>
                  <div className="stat-item stat-high">
                    <div className="stat-value">{ruleStats.high}</div>
                    <div className="stat-label">严重</div>
                  </div>
                </Col>
                <Col span={6}>
                  <div className="stat-item stat-medium">
                    <div className="stat-value">{ruleStats.medium}</div>
                    <div className="stat-label">普通</div>
                  </div>
                </Col>
                <Col span={6}>
                  <div className="stat-item stat-low">
                    <div className="stat-value">{ruleStats.low}</div>
                    <div className="stat-label">轻微</div>
                  </div>
                </Col>
              </Row>
            </Card>
          )}
        </Space>
      </div>
    )
  }

  // 渲染审核Skills配置
  const renderReviewSkills = () => {
    // 搜索过滤
    const filteredSkills = skillsSearchText
      ? reviewSkills.filter(s =>
          s.name.toLowerCase().includes(skillsSearchText.toLowerCase()) ||
          s.description?.toLowerCase().includes(skillsSearchText.toLowerCase())
        )
      : reviewSkills

    // 区分已启用和未启用的 Skills
    const enabledSkills = filteredSkills.filter(s => s.enabled)
    const availableSkills = filteredSkills.filter(s => !s.enabled)

    // 按分类分组
    const groupSkills = (skills: ReviewSkill[]) => {
      const groups: Record<string, ReviewSkill[]> = {}
      skills.forEach(skill => {
        const category = skill.category || 'other'
        if (!groups[category]) {
          groups[category] = []
        }
        groups[category].push(skill)
      })
      return groups
    }

    const enabledGroups = groupSkills(enabledSkills)
    const availableGroups = groupSkills(availableSkills)

    // 分类名称映射
    const categoryNames: Record<string, string> = {
      review: '审核',
      writing: '写作',
      analysis: '分析',
      dialogue: '对话',
      character: '角色',
      plot: '剧情',
      other: '其他'
    }

    return (
      <div style={{ maxWidth: 1000, margin: '0 auto', paddingBottom: '40px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
          <Title level={4} style={{ margin: 0 }}>审核Skills</Title>
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => navigate(`/skills?create=true&category=review`, {
                state: { redirect: `/projects/${projectId}`, activeTab: 'review', reviewSubTab: 'config' }
              })}
            >
              创建新Skill
            </Button>
            <Button
              icon={<SaveOutlined />}
              onClick={loadReviewSkills}
            >
              保存
            </Button>
          </Space>
        </div>

        <Alert
          message="审核Skills说明"
          description="从Skills库中选择任意Skill作为审核Skill。支持搜索和按分类浏览。"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />

        {/* 搜索框 */}
        <Input
          placeholder="搜索Skills..."
          prefix={<InfoCircleOutlined />}
          allowClear
          value={skillsSearchText}
          onChange={e => setSkillsSearchText(e.target.value)}
          style={{ marginBottom: 24 }}
        />

        {/* 已启用的 Skills - 按分类分组 */}
        {Object.keys(enabledGroups).length > 0 && (
          <>
            <div style={{ marginBottom: 16, display: 'flex', alignItems: 'center', gap: 8 }}>
              <CheckCircleOutlined style={{ color: '#52c41a' }} />
              <Text strong>已启用的 Skills ({enabledSkills.length})</Text>
            </div>
            {Object.entries(enabledGroups).map(([category, skills]) => (
              <div key={category} style={{ marginBottom: 24 }}>
                <div style={{ marginBottom: 12, display: 'flex', alignItems: 'center', gap: 8 }}>
                  <Tag color="success">{categoryNames[category] || category}</Tag>
                  <Text type="secondary" style={{ fontSize: 12 }}>{skills.length} 个</Text>
                </div>
                <Row gutter={[16, 16]}>
                  {skills.map((skill) => (
                    <Col span={12} key={skill.id}>
                      <Card
                        size="small"
                        style={{
                          border: '1px solid #1890ff',
                          background: '#f0f9ff'
                        }}
                        actions={[
                          <Button
                            key="toggle"
                            danger
                            size="small"
                            onClick={() => handleToggleSkill(skill.id, false)}
                          >
                            禁用
                          </Button>,
                          <Button
                            key="edit"
                            size="small"
                            icon={<EditOutlined />}
                            onClick={() => navigate(`/skills?edit=${skill.id}`, {
                              state: { redirect: `/projects/${projectId}`, activeTab: 'review', reviewSubTab: 'config' }
                            })}
                          >
                            编辑
                          </Button>
                        ]}
                      >
                        <Space direction="vertical" style={{ width: '100%' }} size="small">
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                            <Text strong>{skill.name}</Text>
                            <Tag color="success" style={{ fontSize: 11 }}>已启用</Tag>
                          </div>
                          {skill.description && (
                            <Paragraph
                              type="secondary"
                              ellipsis={{ rows: 2 }}
                              style={{ margin: 0, fontSize: 12 }}
                            >
                              {skill.description}
                            </Paragraph>
                          )}
                        </Space>
                      </Card>
                    </Col>
                  ))}
                </Row>
              </div>
            ))}
          </>
        )}

        {/* 可用的 Skills - 按分类分组 */}
        {Object.keys(availableGroups).length > 0 && (
          <>
            <Divider />
            <div style={{ marginBottom: 16, display: 'flex', alignItems: 'center', gap: 8 }}>
              <PlusCircleOutlined style={{ color: '#8c8c8c' }} />
              <Text strong>可用的 Skills ({availableSkills.length})</Text>
            </div>
            {Object.entries(availableGroups).map(([category, skills]) => (
              <div key={category} style={{ marginBottom: 24 }}>
                <div style={{ marginBottom: 12, display: 'flex', alignItems: 'center', gap: 8 }}>
                  <Tag>{categoryNames[category] || category}</Tag>
                  <Text type="secondary" style={{ fontSize: 12 }}>{skills.length} 个</Text>
                </div>
                <Row gutter={[16, 16]}>
                  {skills.map((skill) => (
                    <Col span={12} key={skill.id}>
                      <Card
                        size="small"
                        style={{
                          border: '1px solid #d9d9d9',
                          background: '#fafafa'
                        }}
                        actions={[
                          <Button
                            key="toggle"
                            type="primary"
                            size="small"
                            onClick={() => handleToggleSkill(skill.id, true)}
                          >
                            启用
                          </Button>,
                          <Button
                            key="edit"
                            size="small"
                            icon={<EditOutlined />}
                            onClick={() => navigate(`/skills?edit=${skill.id}`, {
                              state: { redirect: `/projects/${projectId}`, activeTab: 'review', reviewSubTab: 'config' }
                            })}
                          >
                            编辑
                          </Button>
                        ]}
                      >
                        <Space direction="vertical" style={{ width: '100%' }} size="small">
                          <Text strong>{skill.name}</Text>
                          {skill.description && (
                            <Paragraph
                              type="secondary"
                              ellipsis={{ rows: 2 }}
                              style={{ margin: 0, fontSize: 12 }}
                            >
                              {skill.description}
                            </Paragraph>
                          )}
                        </Space>
                      </Card>
                    </Col>
                  ))}
                </Row>
              </div>
            ))}
          </>
        )}

        {/* 搜索无结果 */}
        {skillsSearchText && filteredSkills.length === 0 && (
          <Empty
            description="没有找到匹配的Skills"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            style={{ padding: '60px 0' }}
          >
            <Button onClick={() => setSkillsSearchText('')}>清除搜索</Button>
          </Empty>
        )}

        {/* 完全空状态 */}
        {!skillsSearchText && reviewSkills.length === 0 && (
          <Empty
            description='暂无审核Skills，点击上方"创建新Skill"按钮添加'
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            style={{ padding: '60px 0' }}
          />
        )}
      </div>
    )
  }

  // 渲染自定义规则
  const renderCustomRules = () => {
    return (
      <div style={{ maxWidth: 1000, margin: '0 auto', paddingBottom: '40px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
          <Title level={4} style={{ margin: 0 }}>自定义审核规则</Title>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setEditingRule(null)
              form.resetFields()
              setRuleModalVisible(true)
            }}
          >
            添加规则
          </Button>
        </div>

        {customRules.length > 0 ? (
          <Row gutter={[16, 16]}>
            {customRules.map((rule) => {
              const categoryInfo = categoryOptions.find(c => c.value === (rule.category || rule.dimension || 'other')) || categoryOptions[6]
              const severityInfo = severityConfig[rule.severity as keyof typeof severityConfig] || severityConfig.medium

              return (
                <Col span={24} key={rule.id}>
                  <Card
                    size="small"
                    style={{
                      borderLeft: `4px solid ${severityInfo.color}`,
                      background: '#fff'
                    }}
                    actions={[
                      <Button
                        key="edit"
                        size="small"
                        icon={<EditOutlined />}
                        onClick={() => {
                          setEditingRule(rule)
                          form.setFieldsValue({
                            ruleName: rule.name,
                            ruleDescription: rule.description,
                            category: rule.category || rule.dimension || 'other',
                            triggerCondition: rule.triggerCondition,
                            severity: rule.severity
                          })
                          setRuleModalVisible(true)
                        }}
                      >
                        编辑
                      </Button>,
                      <Button
                        key="delete"
                        size="small"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={() => handleDeleteRule(rule.id)}
                      >
                        删除
                      </Button>
                    ]}
                  >
                    <Row gutter={16}>
                      <Col span={16}>
                        <Space direction="vertical" style={{ width: '100%' }} size="small">
                          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                            <Text strong style={{ fontSize: 15 }}>{rule.name}</Text>
                            <Tag
                              icon={categoryInfo.icon}
                              color={categoryInfo.color}
                              style={{ fontSize: 11 }}
                            >
                              {categoryInfo.label}
                            </Tag>
                            <Tag
                              icon={severityInfo.icon}
                              style={{
                                fontSize: 11,
                                background: severityInfo.bgColor,
                                color: severityInfo.color,
                                border: `1px solid ${severityInfo.color}`
                              }}
                            >
                              {severityInfo.label}
                            </Tag>
                          </div>
                          <Text type="secondary" style={{ fontSize: 13 }}>{rule.description}</Text>
                          <div style={{
                            padding: '8px 12px',
                            background: '#f6f8fa',
                            borderRadius: '4px',
                            fontSize: 12
                          }}>
                            <Text type="secondary">
                              <BulbOutlined style={{ marginRight: 4 }} />
                              触发条件: {rule.triggerCondition}
                            </Text>
                          </div>
                        </Space>
                      </Col>
                      <Col span={8}>
                        <div style={{
                          textAlign: 'center',
                          padding: '12px',
                          background: severityInfo.bgColor,
                          borderRadius: '8px',
                          border: `1px solid ${severityInfo.color}40`
                        }}>
                          <div style={{ fontSize: 24, marginBottom: 4 }}>
                            {severityInfo.icon}
                          </div>
                          <Text strong style={{ color: severityInfo.color, fontSize: 13 }}>
                            {severityInfo.label}严重度
                          </Text>
                        </div>
                      </Col>
                    </Row>
                  </Card>
                </Col>
              )
            })}
          </Row>
        ) : (
          <Empty
            description="暂无自定义规则"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            style={{ padding: '60px 0' }}
          >
            <Button type="primary" icon={<PlusOutlined />} onClick={() => {
              setEditingRule(null)
              form.resetFields()
              setRuleModalVisible(true)
            }}>
              添加第一条规则
            </Button>
          </Empty>
        )}
      </div>
    )
  }

  // 渲染Agent指令预览
  const renderAgentPromptPreview = () => {
    return (
      <div style={{ maxWidth: 1000, margin: '0 auto', paddingBottom: '40px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24 }}>
          <div>
            <Title level={4} style={{ margin: 0 }}>Agent指令预览</Title>
            <Text type="secondary" style={{ fontSize: 12 }}>
              自动整合所有配置的Agent指令格式
            </Text>
          </div>
          <Space>
            <Button
              icon={<ReloadOutlined />}
              onClick={handleRefreshAll}
              loading={loading}
            >
              刷新
            </Button>
            {agentPromptPreview && (
              <Button
                type="primary"
                icon={<SaveOutlined />}
                onClick={() => {
                  navigator.clipboard.writeText(agentPromptPreview)
                  message.success('已复制到剪贴板')
                }}
              >
                复制指令
              </Button>
            )}
          </Space>
        </div>

        <Alert
          message="Agent指令说明"
          description="此页面自动整合所有审核配置（模式、维度、Skills、规则）为Agent可理解的指令格式，Agent审核时会自动使用这些配置。"
          type="info"
          showIcon
          style={{ marginBottom: 24 }}
        />

        {agentPromptPreview ? (
          <Card
            title={<><SettingOutlined /> 生成的Agent指令</>}
            extra={<Tag color="blue">自动更新</Tag>}
          >
            <pre
              style={{
                whiteSpace: 'pre-wrap',
                fontFamily: 'Monaco, Consolas, monospace',
                fontSize: '13px',
                lineHeight: '1.8',
                maxHeight: '500px',
                overflowY: 'auto',
                background: '#f6f8fa',
                padding: '16px',
                borderRadius: '6px',
                border: '1px solid #e1e4e8',
                margin: 0
              }}
            >
              {agentPromptPreview}
            </pre>
          </Card>
        ) : (
          <Empty
            description="暂无配置数据"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            style={{ padding: '60px 0' }}
          >
            <Text type="secondary">请先配置审核Skills或自定义规则</Text>
          </Empty>
        )}
      </div>
    )
  }

  // 渲染规则模态框
  const renderRuleModal = () => (
    <Modal
      title={editingRule ? '编辑审核规则' : '添加审核规则'}
      open={ruleModalVisible}
      onCancel={() => {
        setRuleModalVisible(false)
        setEditingRule(null)
        form.resetFields()
      }}
      footer={null}
      width={600}
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={editingRule ? (values) => handleUpdateRule(editingRule.id, values) : handleCreateRule}
      >
        <Form.Item
          name="ruleName"
          label="规则名称"
          rules={[{ required: true, message: '请输入规则名称' }]}
        >
          <Input placeholder="例如: 角色性格一致性检查" />
        </Form.Item>

        <Form.Item
          name="ruleDescription"
          label="规则描述"
          rules={[{ required: true, message: '请输入规则描述' }]}
        >
          <Input.TextArea rows={2} placeholder="简要描述这条规则的用途..." />
        </Form.Item>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="category"
              label="分类"
              rules={[{ required: true, message: '请选择分类' }]}
            >
              <Select placeholder="选择分类">
                {categoryOptions.map(opt => (
                  <Select.Option key={opt.value} value={opt.value}>
                    {opt.icon} {opt.label}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="severity"
              label="严重程度"
              rules={[{ required: true }]}
            >
              <Select>
                <Select.Option value="low">
                  <Tag icon={<InfoCircleOutlined />} color="success">轻微</Tag>
                </Select.Option>
                <Select.Option value="medium">
                  <Tag icon={<WarningOutlined />} color="warning">普通</Tag>
                </Select.Option>
                <Select.Option value="high">
                  <Tag icon={<CloseCircleOutlined />} color="error">严重</Tag>
                </Select.Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          name="triggerCondition"
          label="触发条件"
          rules={[{ required: true, message: '请输入触发条件' }]}
          extra="使用自然语言描述触发条件"
        >
          <Input.TextArea
            rows={4}
            placeholder="例如: 当角色行为与其性格设定明显不符时触发，需要检查前后行为一致性..."
          />
        </Form.Item>

        <Form.Item style={{ marginBottom: 0 }}>
          <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
            <Button onClick={() => setRuleModalVisible(false)}>
              取消
            </Button>
            <Button type="primary" htmlType="submit" loading={loading}>
              {editingRule ? '更新规则' : '创建规则'}
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Modal>
  )

  // 渲染配置编辑模态框
  const renderConfigModal = () => {
    // 维度列表 - 与后端保持一致
    const dimensionList = [
      { key: 'character_consistency', name: '角色一致性', icon: '👤' },
      { key: 'plot_coherence', name: '剧情连贯性', icon: '📖' },
      { key: 'dialogue_quality', name: '对话质量', icon: '💬' },
      { key: 'pacing', name: '节奏', icon: '⏱️' },
      { key: 'emotional_depth', name: '情感深度', icon: '❤️' },
      { key: 'thematic_strength', name: '主题强度', icon: '🎯' },
      { key: 'quality', name: '整体质量', icon: '⭐' }
    ]

    return (
      <Modal
        title="编辑审核配置"
        open={configModalVisible}
        onCancel={() => setConfigModalVisible(false)}
        footer={null}
        width={700}
      >
        <Form
          form={configForm}
          layout="vertical"
          onFinish={handleSaveConfig}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="preset"
                label="预设模式"
                rules={[{ required: true, message: '请选择预设模式' }]}
              >
                <Select>
                  <Select.Option value="draft">草稿模式</Select.Option>
                  <Select.Option value="standard">标准模式</Select.Option>
                  <Select.Option value="strict">严格模式</Select.Option>
                  <Select.Option value="custom">自定义模式</Select.Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="pass_threshold"
                label="通过阈值"
                rules={[{ required: true, message: '请输入通过阈值' }]}
              >
                <Select>
                  <Select.Option value={50}>50分</Select.Option>
                  <Select.Option value={60}>60分</Select.Option>
                  <Select.Option value={70}>70分</Select.Option>
                  <Select.Option value={75}>75分</Select.Option>
                  <Select.Option value={80}>80分</Select.Option>
                  <Select.Option value={85}>85分</Select.Option>
                  <Select.Option value={90}>90分</Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="overall_strictness"
            label="整体严格度"
            rules={[{ required: true, message: '请设置整体严格度' }]}
          >
            <Slider
              min={0}
              max={100}
              marks={{
                0: '宽松',
                50: '中等',
                100: '严格'
              }}
            />
          </Form.Item>

          <Divider orientation="left">维度配置</Divider>

          <Form.Item label="审核维度">
            <Form.List name="dimensions">
              {() => (
                <Space direction="vertical" style={{ width: '100%' }} size="middle">
                  {dimensionList.map((dim) => (
                    <Card key={dim.key} size="small" style={{ background: '#fafafa' }}>
                      <Row gutter={16} align="middle">
                        <Col span={6}>
                          <Space>
                            <span style={{ fontSize: 16 }}>{dim.icon}</span>
                            <Text strong>{dim.name}</Text>
                          </Space>
                        </Col>
                        <Col span={4}>
                          <Form.Item
                            name={[dim.key, 'enabled']}
                            valuePropName="checked"
                            style={{ margin: 0 }}
                          >
                            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
                          </Form.Item>
                        </Col>
                        <Col span={7}>
                          <Form.Item
                            name={[dim.key, 'strictness']}
                            label="严格度"
                            style={{ margin: 0, marginBottom: 8 }}
                          >
                            <Slider
                              min={0}
                              max={100}
                              marks={{ 0: '0', 50: '50', 100: '100' }}
                              style={{ marginTop: 8 }}
                            />
                          </Form.Item>
                        </Col>
                        <Col span={7}>
                          <Form.Item
                            name={[dim.key, 'weight']}
                            label="权重"
                            style={{ margin: 0, marginBottom: 8 }}
                          >
                            <Slider
                              min={0}
                              max={1}
                              step={0.1}
                              marks={{ 0: '0', 0.5: '0.5', 1: '1' }}
                              style={{ marginTop: 8 }}
                            />
                          </Form.Item>
                        </Col>
                      </Row>
                    </Card>
                  ))}
                </Space>
              )}
            </Form.List>
          </Form.Item>

          <Form.Item style={{ marginBottom: 0, marginTop: 24 }}>
            <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
              <Button onClick={() => setConfigModalVisible(false)}>
                取消
              </Button>
              <Button type="primary" htmlType="submit" loading={loading}>
                保存配置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    )
  }

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', padding: '8px 0' }}>
      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        type="card"
        style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}
        className="review-config-tabs"
        items={[
          {
            key: 'overview',
            label: <span><InfoCircleOutlined /> 配置摘要</span>,
            children: <div className="tab-content-wrapper">{renderConfigSummary()}</div>
          },
          {
            key: 'skills',
            label: <span><SettingOutlined /> 审核Skills</span>,
            children: <div className="tab-content-wrapper">{renderReviewSkills()}</div>
          },
          {
            key: 'rules',
            label: <span><BulbOutlined /> 自定义规则</span>,
            children: <div className="tab-content-wrapper">{renderCustomRules()}</div>
          },
          {
            key: 'preview',
            label: <span><FileTextOutlined /> Agent指令</span>,
            children: <div className="tab-content-wrapper">{renderAgentPromptPreview()}</div>
          }
        ]}
      />

      {/* 规则模态框 */}
      {renderRuleModal()}

      {/* 配置编辑模态框 */}
      {renderConfigModal()}

      <style>{`
        .review-config-tabs {
          display: flex !important;
          flex-direction: column !important;
        }
        .review-config-tabs .ant-tabs-nav {
          flex-shrink: 0;
          margin-bottom: 8px;
        }
        .review-config-tabs .ant-tabs-content-holder {
          flex: 1;
          overflow: hidden;
        }
        .review-config-tabs .ant-tabs-content {
          height: 100%;
        }
        .review-config-tabs .ant-tabs-tabpane {
          height: 100%;
        }
        .tab-content-wrapper {
          height: 100%;
          overflow-y: auto;
          overflow-x: hidden;
          padding: 16px 24px 160px 24px;
          box-sizing: border-box;
          scroll-behavior: smooth;
        }
        .summary-card {
          text-align: center;
          padding: 16px;
        }
        .summary-card .summary-value {
          font-size: 28px;
          font-weight: bold;
          color: #1890ff;
          margin-bottom: 8px;
        }
        .summary-card .summary-label {
          font-size: 13px;
          color: #8c8c8c;
        }
        .stat-item {
          text-align: center;
          padding: 16px;
          background: #fafafa;
          border-radius: 8px;
        }
        .stat-item .stat-value {
          font-size: 24px;
          font-weight: bold;
          margin-bottom: 4px;
        }
        .stat-item .stat-label {
          font-size: 12px;
          color: #8c8c8c;
        }
        .stat-item.stat-high {
          background: #fff1f0;
          border: 1px solid #ffccc7;
        }
        .stat-item.stat-high .stat-value {
          color: #ff4d4f;
        }
        .stat-item.stat-medium {
          background: #fff7e6;
          border: 1px solid #ffd591;
        }
        .stat-item.stat-medium .stat-value {
          color: #fa8c16;
        }
        .stat-item.stat-low {
          background: #f6ffed;
          border: 1px solid #b7eb8f;
        }
        .stat-item.stat-low .stat-value {
          color: #52c41a;
        }
      `}</style>
    </div>
  )
}

export default ReviewConfigPage
