/**
 * 项目详情和执行页面
 *
 * 标签页结构：
 * 1. 项目设置 - 编辑基本信息 + 创作方式选择 + 上传剧本/编辑灵感
 * 2. 全局设定生成 - 根据项目设置进行分析或生成
 * 3. 剧集创作 - 执行剧集创作任务
 * 4. 记忆系统 - 故事记忆管理
 * 5. 审核系统 - 内容质量审核
 */
import { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { Card, Button, Descriptions, List, Tag, Space, Modal, message, Spin, Typography, Tabs, Form, Input, InputNumber, Upload, Alert, Popover, Select } from 'antd'
import { ArrowLeftOutlined, PlayCircleOutlined, CheckCircleOutlined, LoadingOutlined, ClockCircleOutlined, ScanOutlined, FileTextOutlined, SettingOutlined, RobotOutlined, UploadOutlined, EditOutlined, SaveOutlined } from '@ant-design/icons'
import { useProjectStore } from '@/stores/projectStore'
import { useSkillStore } from '@/stores/skillStore'
import { Episode } from '@/services/projectService'
import { taskService } from '@/services/taskService'
import { TaskProgressTracker } from '@/components/TaskProgressTracker'

const { TextParagraph } = Typography
const { TabPane } = Tabs
const { TextArea } = Input

// Skill 选择器和自定义提示词组件
const SkillSelectorWithPrompt = ({
  title,
  icon,
  skills,
  selectedSkills,
  onSkillsChange,
  customPrompt,
  onPromptChange,
  description
}: {
  title: string
  icon: React.ReactNode
  skills: any[]
  selectedSkills: string[]
  onSkillsChange: (skills: string[]) => void
  customPrompt: string
  onPromptChange: (prompt: string) => void
  description?: string
}) => {
  const content = (
    <div style={{ width: '400px' }}>
      <div style={{ marginBottom: '12px', color: '#666', fontSize: '12px' }}>
        {description || '选择用于此 AI 生成任务的技能'}
      </div>
      <Select
        mode="multiple"
        style={{ width: '100%' }}
        placeholder="选择技能"
        value={selectedSkills}
        onChange={onSkillsChange}
        maxTagCount="responsive"
        options={skills.map(skill => ({
          value: skill.id,
          label: skill.name
        }))}
      />
      <div style={{ marginTop: '12px' }}>
        <Space wrap>
          {selectedSkills.map(skillId => {
            const skill = skills.find(s => s.id === skillId)
            return skill ? (
              <Tag
                key={skillId}
                closable
                onClose={() => onSkillsChange(selectedSkills.filter(id => id !== skillId))}
              >
                {skill.name}
              </Tag>
            ) : null
          })}
        </Space>
      </div>
      <div style={{ marginTop: '16px' }}>
        <div style={{ marginBottom: '8px', fontSize: '12px', color: '#666' }}>
          自定义提示词（可选）
        </div>
        <TextArea
          placeholder="添加额外的要求或上下文..."
          value={customPrompt}
          onChange={(e) => onPromptChange(e.target.value)}
          rows={3}
          style={{ fontSize: '12px' }}
        />
      </div>
    </div>
  )

  return (
    <Popover
      content={content}
      title={title}
      trigger="click"
      placement="bottomRight"
    >
      <Button
        icon={icon}
        size="small"
        type={(selectedSkills.length > 0 || customPrompt) ? 'primary' : 'default'}
      >
        {selectedSkills.length > 0 || customPrompt ? `已配置` : '配置'}
      </Button>
    </Popover>
  )
}

export const ProjectDetail = () => {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const { currentProject, projects, episodes, loading, error, fetchProject, fetchEpisodes, executeEpisode, updateProject } = useProjectStore()
  const { skills, fetchSkills } = useSkillStore()
  const [executing, setExecuting] = useState(false)
  const [currentEpisode, setCurrentEpisode] = useState<number>(1)
  const [selectedEpisode, setSelectedEpisode] = useState<Episode | null>(null)
  const [activeTab, setActiveTab] = useState('settings')

  // 项目设置相关状态
  const [settingsForm] = Form.useForm()
  const [updatingSettings, setUpdatingSettings] = useState(false)
  const [creationMode, setCreationMode] = useState<'script' | 'inspiration' | null>(null)
  const [scriptContent, setScriptContent] = useState('')
  const [inspirationContent, setInspirationContent] = useState('')
  const [scriptEditing, setScriptEditing] = useState(false)
  const [inspirationEditing, setInspirationEditing] = useState(false)

  // 全局设定生成相关状态
  const [globalForm] = Form.useForm()
  const [generating, setGenerating] = useState(false)
  const [currentTaskId, setCurrentTaskId] = useState<string | null>(null)
  const [showTaskProgress, setShowTaskProgress] = useState(false)
  const [taskType, setTaskType] = useState<string | null>(null)

  // Skills 配置
  const [worldSkills, setWorldSkills] = useState<string[]>([])
  const [characterSkills, setCharacterSkills] = useState<string[]>([])
  const [outlineSkills, setOutlineSkills] = useState<string[]>([])

  // 自定义提示词
  const [worldPrompt, setWorldPrompt] = useState('')
  const [characterPrompt, setCharacterPrompt] = useState('')
  const [outlinePrompt, setOutlinePrompt] = useState('')

  // 加载 Skills
  useEffect(() => {
    const loadSkills = async () => {
      try {
        await fetchSkills()
      } catch (error) {
        console.error('加载 Skills 失败:', error)
      }
    }
    loadSkills()
  }, [])

  // 加载项目数据后初始化
  useEffect(() => {
    if (currentProject) {
      // 初始化项目设置表单
      settingsForm.setFieldsValue({
        name: currentProject.name,
        totalEpisodes: currentProject.totalEpisodes
      })

      // 确定创作方式
      const hasScript = currentProject.globalContext?.uploadedScript && currentProject.globalContext.uploadedScript.length > 0
      const hasInspiration = currentProject.globalContext?.inspiration && currentProject.globalContext.inspiration.length > 0

      if (hasScript) {
        setCreationMode('script')
        setScriptContent(currentProject.globalContext.uploadedScript || '')
      } else if (hasInspiration) {
        setCreationMode('inspiration')
        setInspirationContent(currentProject.globalContext.inspiration || '')
      }

      // 初始化全局设定表单
      globalForm.setFieldsValue({
        worldSetting: currentProject.globalContext?.worldSetting || '',
        characters: currentProject.globalContext?.characterProfiles || '',
        overallOutline: currentProject.globalContext?.overallOutline || ''
      })
    }
  }, [currentProject])

  useEffect(() => {
    if (id) {
      fetchProject(id)
      fetchEpisodes(id)
    }
  }, [id])

  // 上传剧本文件
  const handleScriptUpload = (file: any) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      const content = e.target?.result as string || ''
      setScriptContent(content)
      setCreationMode('script')
      setScriptEditing(true)
      message.success('剧本上传成功！您可以编辑内容后点击保存')
    }
    reader.readAsText(file)
    return false
  }

  // 上传灵感文件
  const handleInspirationUpload = (file: any) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      const content = e.target?.result as string || ''
      setInspirationContent(content)
      setCreationMode('inspiration')
      setInspirationEditing(true)
      message.success('灵感文件上传成功！您可以编辑内容后点击保存')
    }
    reader.readAsText(file)
    return false
  }

  // 保存项目设置
  const handleSaveSettings = async () => {
    try {
      await settingsForm.validateFields()

      // 验证必须选择了创作方式并填写了内容
      if (!creationMode) {
        message.error('请选择创作方式并填写相应内容')
        return
      }

      if (creationMode === 'script' && !scriptContent.trim()) {
        message.error('请上传或填写剧本内容')
        return
      }

      if (creationMode === 'inspiration' && !inspirationContent.trim()) {
        message.error('请上传或填写灵感内容')
        return
      }

      setUpdatingSettings(true)
      const values = settingsForm.getFieldsValue()

      await updateProject(id!, {
        name: values.name,
        totalEpisodes: values.totalEpisodes,
        globalContext: {
          ...currentProject?.globalContext,
          uploadedScript: scriptContent,
          inspiration: inspirationContent
        }
      })

      message.success('项目设置已保存')
      await fetchProject(id!)

      // 自动跳转到全局设定生成标签页
      setActiveTab('global-generation')
    } catch (error: any) {
      if (error.errorFields) {
        return
      }
      message.error(`保存失败: ${error.message || '未知错误'}`)
    } finally {
      setUpdatingSettings(false)
    }
  }

  // AI生成/分析世界观
  const handleGenerateWorld = async () => {
    if (!id) return

    const projectName = currentProject?.name || '未命名项目'
    const selectedSkillsInfo = skills.filter(s => worldSkills.includes(s.id))

    // 根据创作方式决定是分析还是生成
    const isAnalysis = creationMode === 'script'
    const baseContent = isAnalysis ? scriptContent : inspirationContent
    const idea = isAnalysis
      ? `分析以下剧本，提取世界观设定：\n${baseContent?.substring(0, 2000)}`
      : `项目名称：${projectName}\n创意灵感：\n${baseContent}`

    try {
      setGenerating(true)
      const response = await taskService.generateWorld({
        idea,
        projectName,
        genre: '古风',
        skills: selectedSkillsInfo.map(s => ({
          id: s.id,
          name: s.name,
          behavior: s.behavior_guide
        })),
        customPrompt: worldPrompt || undefined,
        projectId: id
      })

      setCurrentTaskId(response.taskId)
      setTaskType('generate_world')
      setShowTaskProgress(true)
    } catch (error: any) {
      message.error(`创建任务失败: ${error.message || '未知错误'}`)
      setGenerating(false)
    }
  }

  // AI生成/分析人物设定
  const handleGenerateCharacters = async () => {
    if (!id) return

    const projectName = currentProject?.name || '未命名项目'
    const totalEpisodes = currentProject?.totalEpisodes || 30
    const selectedSkillsInfo = skills.filter(s => characterSkills.includes(s.id))

    const isAnalysis = creationMode === 'script'
    const baseContent = isAnalysis ? scriptContent : inspirationContent
    const idea = isAnalysis
      ? `分析以下剧本，提取人物设定：\n${baseContent?.substring(0, 2000)}`
      : `项目名称：${projectName}，总集数：${totalEpisodes}集\n创意灵感：\n${baseContent}`

    try {
      setGenerating(true)
      const response = await taskService.generateCharacters({
        idea,
        projectName,
        totalEpisodes,
        skills: selectedSkillsInfo.map(s => ({
          id: s.id,
          name: s.name,
          behavior: s.behavior_guide
        })),
        customPrompt: characterPrompt || undefined,
        projectId: id
      })

      setCurrentTaskId(response.taskId)
      setTaskType('generate_characters')
      setShowTaskProgress(true)
    } catch (error: any) {
      message.error(`创建任务失败: ${error.message || '未知错误'}`)
      setGenerating(false)
    }
  }

  // AI生成/分析大纲
  const handleGenerateOutline = async () => {
    if (!id) return

    const projectName = currentProject?.name || '未命名项目'
    const totalEpisodes = currentProject?.totalEpisodes || 30
    const selectedSkillsInfo = skills.filter(s => outlineSkills.includes(s.id))

    const isAnalysis = creationMode === 'script'
    const baseContent = isAnalysis ? scriptContent : inspirationContent
    const idea = isAnalysis
      ? `分析以下剧本，提取整体大纲：\n${baseContent?.substring(0, 2000)}`
      : `项目名称：${projectName}，总集数：${totalEpisodes}集\n创意灵感：\n${baseContent}`

    try {
      setGenerating(true)
      const response = await taskService.generateOutline({
        idea,
        totalEpisodes,
        genre: '古风',
        projectName,
        skills: selectedSkillsInfo.map(s => ({
          id: s.id,
          name: s.name,
          behavior: s.behavior_guide
        })),
        customPrompt: outlinePrompt || undefined,
        projectId: id
      })

      setCurrentTaskId(response.taskId)
      setTaskType('generate_outline')
      setShowTaskProgress(true)
    } catch (error: any) {
      message.error(`创建任务失败: ${error.message || '未知错误'}`)
      setGenerating(false)
    }
  }

  // 任务完成回调
  const handleTaskComplete = (result: any) => {
    setShowTaskProgress(false)
    setGenerating(false)

    if (taskType === 'generate_world') {
      const worldSetting = result?.worldSetting || result
      globalForm.setFieldsValue({ worldSetting })
      message.success('世界观设定生成完成！')
    } else if (taskType === 'generate_characters') {
      const characters = result?.characters || result
      globalForm.setFieldsValue({ characters })
      message.success('人物设定生成完成！')
    } else if (taskType === 'generate_outline') {
      const outline = result?.outline || result
      globalForm.setFieldsValue({ overallOutline: outline })
      message.success('大纲生成完成！')
    }
  }

  // 任务失败回调
  const handleTaskError = (error: string) => {
    setShowTaskProgress(false)
    setGenerating(false)
    message.error(`任务执行失败: ${error}`)
  }

  // 保存全局设定
  const handleSaveGlobalSettings = async () => {
    try {
      const worldSetting = globalForm.getFieldValue('worldSetting')
      const characters = globalForm.getFieldValue('characters')
      const overallOutline = globalForm.getFieldValue('overallOutline')

      await updateProject(id!, {
        globalContext: {
          ...currentProject?.globalContext,
          worldSetting: worldSetting || '',
          overallOutline: overallOutline || '',
          characterProfiles: characters ? {} : {},
          sceneSettings: {}
        }
      })

      message.success('全局设定已保存')
      await fetchProject(id!)
    } catch (error: any) {
      message.error(`保存失败: ${error.message || '未知错误'}`)
    }
  }

  // 执行剧集创作
  const handleExecuteEpisode = async (epNum: number) => {
    setExecuting(true)
    try {
      await executeEpisode(id!, epNum)
      message.success(`EP${epNum} 创作完成！`)
      await fetchEpisodes(id!)
    } catch (error) {
      message.error(`创作失败: ${(error as Error).message}`)
    } finally {
      setExecuting(false)
    }
  }

  const handleExecuteBatch = async () => {
    setExecuting(true)
    try {
      for (let i = 1; i <= 3; i++) {
        await executeEpisode(id!, i)
        message.success(`EP${i} 创作完成！`)
      }
      await fetchEpisodes(id!)
      message.success('批次创作完成！')
    } catch (error) {
      message.error(`批量创作失败: ${(error as Error).message}`)
    } finally {
      setExecuting(false)
    }
  }

  const getStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      'pending': 'default',
      'writing': 'processing',
      'completed': 'success',
      'needs-review': 'warning'
    }
    return colors[status] || 'default'
  }

  const getStatusText = (status: string) => {
    const texts: Record<string, string> = {
      'pending': '待开始',
      'writing': '创作中',
      'completed': '已完成',
      'needs-review': '需审核'
    }
    return texts[status] || status
  }

  // 检查是否可以进入全局设定生成
  const canProceedToGlobalGeneration = creationMode &&
    ((creationMode === 'script' && scriptContent.trim()) ||
     (creationMode === 'inspiration' && inspirationContent.trim()))

  // 检查全局设定是否完成
  const globalSettingsCompleted = currentProject?.globalContext?.worldSetting?.trim() &&
    currentProject?.globalContext?.overallOutline?.trim()

  // 错误处理
  if (error) {
    return (
      <div style={{ padding: '50px', textAlign: 'center' }}>
        <Alert
          message="加载失败"
          description={error}
          type="error"
          showIcon
          action={
            <Button type="primary" onClick={() => window.location.reload()}>
              刷新页面
            </Button>
          }
        />
      </div>
    )
  }

  // 加载中
  if (loading || !currentProject) {
    return (
      <div style={{ padding: '50px', textAlign: 'center' }}>
        <Spin size="large" />
      </div>
    )
  }

  const isAnalysisMode = creationMode === 'script'

  return (
    <div style={{ padding: '24px' }}>
      {/* 头部 */}
      <Card style={{ marginBottom: '16px' }}>
        <Space direction="vertical" style={{ width: '100%' }} size="middle">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div>
              <Button
                icon={<ArrowLeftOutlined />}
                onClick={() => navigate('/projects')}
                style={{
                  marginRight: '16px',
                  borderRadius: '8px',
                  height: '40px',
                  fontWeight: 600,
                  transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.transform = 'translateX(-4px)'
                  e.currentTarget.style.boxShadow = '0 4px 12px rgba(22, 119, 255, 0.15)'
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.transform = 'translateX(0)'
                  e.currentTarget.style.boxShadow = 'none'
                }}
              >
                返回项目列表
              </Button>
              <span style={{ fontSize: '14px', color: '#999', marginLeft: '8px' }}>
                共 {projects.length} 个项目
              </span>
            </div>
            <h1 style={{ margin: 0 }}>{currentProject.name}</h1>
          </div>
          <Descriptions column={2} size="small">
            <Descriptions.Item label="总集数">{currentProject.totalEpisodes}</Descriptions.Item>
            <Descriptions.Item label="模式">{currentProject.mode}</Descriptions.Item>
            <Descriptions.Item label="创建时间">
              {new Date(currentProject.createdAt).toLocaleString()}
            </Descriptions.Item>
            <Descriptions.Item label="Agent">{currentProject.agentId}</Descriptions.Item>
          </Descriptions>
        </Space>
      </Card>

      {/* 标签页 */}
      <Card>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          {/* 项目设置标签页 */}
          <TabPane
            tab={
              <span>
                <SettingOutlined />
                项目设置
              </span>
            }
            key="settings"
          >
            <Alert
              message="项目基本设置"
              description="编辑项目信息，选择创作方式并上传/填写相关内容"
              type="info"
              showIcon
              style={{ marginBottom: '16px' }}
            />
            <Form form={settingsForm} layout="vertical" style={{ maxWidth: '800px' }}>
              <Form.Item label="项目名称" name="name" rules={[{ required: true, message: '请填写项目名称' }]}>
                <Input placeholder="例如：宫廷风云" />
              </Form.Item>

              <Form.Item label="总集数" name="totalEpisodes" rules={[{ required: true, message: '请填写总集数' }]}>
                <InputNumber min={1} max={500} style={{ width: '100%' }} />
              </Form.Item>

              {/* 创作方式选择 */}
              <Form.Item label="选择创作方式" required>
                <Space direction="vertical" style={{ width: '100%' }} size="middle">
                  <Card
                    size="small"
                    title="剧本改编"
                    style={{
                      cursor: 'pointer',
                      border: creationMode === 'script' ? '2px solid #1677ff' : undefined,
                      backgroundColor: creationMode === 'script' ? '#f0f5ff' : undefined
                    }}
                    onClick={() => {
                      setCreationMode('script')
                      setScriptEditing(true)
                    }}
                  >
                    <div onClick={(e) => e.stopPropagation()}>
                      <p style={{ margin: 0, marginBottom: '12px', color: '#666' }}>
                        上传现有剧本，AI将分析并提取世界观、人物设定和大纲
                      </p>
                      {!scriptEditing ? (
                        <Upload.Dragger
                          name="script"
                          multiple={false}
                          accept=".txt,.md,.docx"
                          showUploadList={false}
                          beforeUpload={handleScriptUpload}
                          style={{ padding: '16px' }}
                        >
                          <p className="ant-upload-drag-icon">
                            <UploadOutlined style={{ fontSize: '24px', color: '#1677ff' }} />
                          </p>
                          <p className="ant-upload-text">点击或拖拽文件到此区域上传剧本</p>
                          <p className="ant-upload-hint">支持 .txt, .md, .docx 格式</p>
                        </Upload.Dragger>
                      ) : (
                        <div>
                          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                            <Space>
                              <Tag color="success">剧本内容 ({scriptContent.length} 字符)</Tag>
                              <Button size="small" icon={<EditOutlined />} onClick={() => setScriptEditing(true)}>
                                编辑
                              </Button>
                            </Space>
                          </div>
                          {scriptEditing && (
                            <>
                              <TextArea
                                value={scriptContent}
                                onChange={(e) => setScriptContent(e.target.value)}
                                rows={10}
                                placeholder="剧本内容..."
                                style={{ marginBottom: '8px' }}
                              />
                              <Space>
                                <Button size="small" onClick={() => setScriptEditing(false)}>
                                  完成编辑
                                </Button>
                                <Button size="small" danger onClick={() => setScriptContent('')}>
                                  清除内容
                                </Button>
                              </Space>
                            </>
                          )}
                        </div>
                      )}
                    </div>
                  </Card>

                  <Card
                    size="small"
                    title="从头创作"
                    style={{
                      cursor: 'pointer',
                      border: creationMode === 'inspiration' ? '2px solid #1677ff' : undefined,
                      backgroundColor: creationMode === 'inspiration' ? '#f0f5ff' : undefined
                    }}
                    onClick={() => {
                      setCreationMode('inspiration')
                      setInspirationEditing(true)
                    }}
                  >
                    <div onClick={(e) => e.stopPropagation()}>
                      <p style={{ margin: 0, marginBottom: '12px', color: '#666' }}>
                        描述您的创意灵感，AI将根据灵感生成完整的世界观、人物设定和大纲
                      </p>
                      {!inspirationEditing ? (
                        <>
                          <TextArea
                            placeholder="描述您的创意灵感、故事构思..."
                            rows={4}
                            value={inspirationContent}
                            onChange={(e) => setInspirationContent(e.target.value)}
                            style={{ marginBottom: '8px' }}
                          />
                          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                            <span style={{ fontSize: '12px', color: '#999' }}>或上传灵感文件</span>
                            <Upload.Dragger
                              name="inspiration"
                              multiple={false}
                              accept=".txt,.md,.docx"
                              showUploadList={false}
                              beforeUpload={handleInspirationUpload}
                              style={{ padding: '12px', width: '300px' }}
                            >
                              <p className="ant-upload-drag-icon">
                                <UploadOutlined style={{ fontSize: '20px', color: '#1677ff' }} />
                              </p>
                              <p className="ant-upload-text">上传灵感文件</p>
                            </Upload.Dragger>
                          </div>
                        </>
                      ) : (
                          <div>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                              <Space>
                                <Tag color="processing">灵感内容 ({inspirationContent.length} 字符)</Tag>
                                <Button size="small" icon={<EditOutlined />} onClick={() => setInspirationEditing(true)}>
                                  编辑
                                </Button>
                              </Space>
                            </div>
                            <TextArea
                              value={inspirationContent}
                              onChange={(e) => setInspirationContent(e.target.value)}
                              rows={10}
                              placeholder="创意灵感内容..."
                              style={{ marginBottom: '8px' }}
                            />
                            <Space>
                              <Button size="small" onClick={() => setInspirationEditing(false)}>
                                完成编辑
                              </Button>
                              <Button size="small" danger onClick={() => setInspirationContent('')}>
                                清除内容
                              </Button>
                            </Space>
                          </div>
                        )}
                    </div>
                  </Card>
                </Space>
              </Form.Item>

              <Form.Item>
                <Space>
                  <Button type="primary" loading={updatingSettings} onClick={handleSaveSettings} icon={<SaveOutlined />}>
                    保存设置
                  </Button>
                  {canProceedToGlobalGeneration && (
                    <Button onClick={() => setActiveTab('global-generation')}>
                      下一步：全局设定生成
                    </Button>
                  )}
                </Space>
              </Form.Item>
            </Form>
          </TabPane>

          {/* 全局设定生成标签页 */}
          <TabPane
            tab={
              <span>
                <RobotOutlined />
                全局设定生成
              </span>
            }
            key="global-generation"
          >
            {!canProceedToGlobalGeneration ? (
              <Alert
                message="请先完成项目设置"
                description="请在项目设置中选择创作方式并填写剧本或灵感内容"
                type="warning"
                showIcon
                action={
                  <Button type="primary" onClick={() => setActiveTab('settings')}>
                    前往设置
                  </Button>
                }
              />
            ) : (
              <Space direction="vertical" size="large" style={{ width: '100%' }}>
                <Alert
                  message={isAnalysisMode ? "全局设定分析" : "全局设定生成"}
                  description={
                    isAnalysisMode
                      ? "AI将分析您上传的剧本，提取世界观、人物设定和整体大纲"
                      : "AI将根据您的创意灵感，生成世界观、人物设定和整体大纲"
                  }
                  type="info"
                  showIcon
                />

                <Form form={globalForm} layout="vertical">
                  {/* 世界观设定 */}
                  <Card
                    title="世界观设定"
                    size="small"
                    extra={
                      <Space>
                        <SkillSelectorWithPrompt
                          title="配置世界观生成"
                          icon={<SettingOutlined />}
                          skills={skills}
                          selectedSkills={worldSkills}
                          onSkillsChange={setWorldSkills}
                          customPrompt={worldPrompt}
                          onPromptChange={setWorldPrompt}
                        />
                        <Button
                          type="primary"
                          size="small"
                          icon={generating ? <LoadingOutlined /> : <RobotOutlined />}
                          onClick={handleGenerateWorld}
                          disabled={generating}
                        >
                          {isAnalysisMode ? 'AI 分析' : 'AI 生成'}
                        </Button>
                      </Space>
                    }
                    style={{ marginBottom: '16px' }}
                  >
                    <Form.Item name="worldSetting">
                      <TextArea
                        rows={6}
                        placeholder={
                          isAnalysisMode
                            ? "点击AI分析，从剧本中提取世界观设定..."
                            : "点击AI生成，根据灵感创建世界观设定..."
                        }
                      />
                    </Form.Item>
                  </Card>

                  {/* 人物设定 */}
                  <Card
                    title="人物设定"
                    size="small"
                    extra={
                      <Space>
                        <SkillSelectorWithPrompt
                          title="配置人物生成"
                          icon={<SettingOutlined />}
                          skills={skills}
                          selectedSkills={characterSkills}
                          onSkillsChange={setCharacterSkills}
                          customPrompt={characterPrompt}
                          onPromptChange={setCharacterPrompt}
                        />
                        <Button
                          type="primary"
                          size="small"
                          icon={generating ? <LoadingOutlined /> : <RobotOutlined />}
                          onClick={handleGenerateCharacters}
                          disabled={generating}
                        >
                          {isAnalysisMode ? 'AI 分析' : 'AI 生成'}
                        </Button>
                      </Space>
                    }
                    style={{ marginBottom: '16px' }}
                  >
                    <Form.Item name="characters">
                      <TextArea
                        rows={6}
                        placeholder={
                          isAnalysisMode
                            ? "点击AI分析，从剧本中提取人物设定..."
                            : "点击AI生成，根据灵感创建人物设定..."
                        }
                      />
                    </Form.Item>
                  </Card>

                  {/* 整体大纲 */}
                  <Card
                    title="整体大纲"
                    size="small"
                    extra={
                      <Space>
                        <SkillSelectorWithPrompt
                          title="配置大纲生成"
                          icon={<SettingOutlined />}
                          skills={skills}
                          selectedSkills={outlineSkills}
                          onSkillsChange={setOutlineSkills}
                          customPrompt={outlinePrompt}
                          onPromptChange={setOutlinePrompt}
                        />
                        <Button
                          type="primary"
                          size="small"
                          icon={generating ? <LoadingOutlined /> : <RobotOutlined />}
                          onClick={handleGenerateOutline}
                          disabled={generating}
                        >
                          {isAnalysisMode ? 'AI 分析' : 'AI 生成'}
                        </Button>
                      </Space>
                    }
                    style={{ marginBottom: '16px' }}
                  >
                    <Form.Item name="overallOutline">
                      <TextArea
                        rows={8}
                        placeholder={
                          isAnalysisMode
                            ? "点击AI分析，从剧本中提取整体大纲..."
                            : "点击AI生成，根据灵感创建整体大纲..."
                        }
                      />
                    </Form.Item>
                  </Card>

                  <Form.Item>
                    <Button type="primary" onClick={handleSaveGlobalSettings} icon={<SaveOutlined />}>
                      保存全局设定
                    </Button>
                  </Form.Item>
                </Form>
              </Space>
            )}
          </TabPane>

          {/* 剧集创作标签页 */}
          <TabPane tab="剧集创作" key="episodes">
            {!globalSettingsCompleted ? (
              <Alert
                message="请先完成全局设定"
                description="开始剧集创作前，请先在「全局设定生成」中完成世界观设定和整体大纲的AI生成或手动填写"
                type="warning"
                showIcon
                action={
                  <Button type="primary" onClick={() => setActiveTab('global-generation')}>
                    前往全局设定生成
                  </Button>
                }
              />
            ) : (
              <Space direction="vertical" style={{ width: '100%' }} size="large">
                <Space style={{ marginBottom: '16px' }}>
                  <Button
                    type="primary"
                    icon={executing ? <LoadingOutlined /> : <PlayCircleOutlined />}
                    onClick={handleExecuteBatch}
                    disabled={executing}
                  >
                    {executing ? '创作中...' : '开始创作 (EP1-EP3)'}
                  </Button>
                  <span style={{ color: '#888' }}>依次创作前3集，使用配置的 Skills</span>
                </Space>

                <List
                  dataSource={episodes}
                  renderItem={(episode) => (
                    <List.Item
                      actions={[
                        episode.status === 'completed' ? (
                          <Button type="link" onClick={() => setSelectedEpisode(episode)}>
                            查看内容
                          </Button>
                        ) : null
                      ]}
                    >
                      <List.Item.Meta
                        title={
                          <Space>
                            <span>EP{episode.number}</span>
                            {episode.title && <span>- {episode.title}</span>}
                            <Tag color={getStatusColor(episode.status)}>
                              {getStatusText(episode.status)}
                            </Tag>
                          </Space>
                        }
                        description={
                          <Space direction="vertical" size="small">
                            {episode.qualityScore && <span>质量分数: {episode.qualityScore}</span>}
                            {episode.issues && episode.issues.length > 0 && <span>问题数: {episode.issues.length}</span>}
                          </Space>
                        }
                      />
                    </List.Item>
                  )}
                />
              </Space>
            )}
          </TabPane>

          {/* 记忆系统标签页 */}
          <TabPane
            tab={
              <span>
                <ClockCircleOutlined />
                记忆系统
              </span>
            }
            key="memory"
          >
            <Space direction="vertical" style={{ width: '100%' }}>
              <p>管理故事记忆元素，包括时间线、剧情线、角色状态、伏笔和关系图。</p>
              <Button type="primary" onClick={() => navigate(`/projects/${id}/memory`)}>
                进入记忆系统
              </Button>
            </Space>
          </TabPane>

          {/* 审核系统标签页 */}
          <TabPane
            tab={
              <span>
                <ScanOutlined />
                审核系统
              </span>
            }
            key="review"
          >
            <Space direction="vertical" style={{ width: '100%' }}>
              <p>配置和执行内容质量审核，查看评分和问题详情。</p>
              <Space>
                <Button onClick={() => navigate(`/projects/${id}/review/config`)}>配置审核</Button>
                <Button type="primary" onClick={() => navigate(`/projects/${id}/review/results`)}>查看结果</Button>
              </Space>
            </Space>
          </TabPane>
        </Tabs>
      </Card>

      {/* 剧集内容弹窗 */}
      <Modal
        title={`EP${selectedEpisode?.number} - ${selectedEpisode?.title}`}
        open={!!selectedEpisode}
        onCancel={() => setSelectedEpisode(null)}
        footer={null}
        width={800}
      >
        {selectedEpisode && (
          <Space direction="vertical" style={{ width: '100%' }} size="large">
            {selectedEpisode.outline && (
              <div>
                <h4>大纲</h4>
                <p>{selectedEpisode.outline}</p>
              </div>
            )}
            {selectedEpisode.content && (
              <div>
                <h4>剧本内容</h4>
                <pre style={{ whiteSpace: 'pre-wrap', background: '#f5f5f5', padding: '16px', borderRadius: '4px' }}>
                  {selectedEpisode.content}
                </pre>
              </div>
            )}
            {selectedEpisode.qualityScore && (
              <div>
                <h4>质量分数: {selectedEpisode.qualityScore}</h4>
              </div>
            )}
          </Space>
        )}
      </Modal>

      {/* AI生成任务进度弹窗 */}
      <Modal
        title="AI 生成进度"
        open={showTaskProgress}
        onCancel={() => setShowTaskProgress(false)}
        footer={null}
        width={600}
        closable={!generating}
      >
        {currentTaskId && (
          <TaskProgressTracker
            taskId={currentTaskId}
            onComplete={handleTaskComplete}
            onError={handleTaskError}
            pollInterval={1000}
          />
        )}
      </Modal>
    </div>
  )
}
