/**
 * 增强的项目创建页面
 * 支持：上传剧本、AI 辅助生成、每个生成点独立配置 Skill
 * 新增：一键生成所有内容、长剧本分段分析、异步任务、进度追踪
 */
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import {
  Form, Input, InputNumber, Button, Card, Steps, message,
  Upload, Select, Space, Divider, Tag, Alert, Popover, Progress, Radio
} from 'antd'
import {
  UploadOutlined, FileTextOutlined, RobotOutlined,
  CheckCircleOutlined, ArrowRightOutlined, SettingOutlined,
  ThunderboltOutlined, EditOutlined
} from '@ant-design/icons'
import { useProjectStore } from '@/stores/projectStore'
import { useSkillStore } from '@/stores/skillStore'
import { api } from '@/services'
import { ProjectCreateRequest } from '@/services/projectService'
import { taskService } from '@/services/taskService'

const { TextArea } = Input
const { Step } = Steps

// 默认 Skill 配置（用于一键生成）
const DEFAULT_SKILLS = {
  worldSetting: ['world_builder'],  // 世界观生成默认技能
  characters: ['character_creator'],  // 人物生成默认技能
  outline: ['story_structurer']  // 大纲生成默认技能
}

// 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>
  )
}

// 保留原有的 Skill 选择器组件（用于向后兼容）
const SkillSelector = ({
  title,
  icon,
  skills,
  selectedSkills,
  onSkillsChange,
  description
}: {
  title: string
  icon: React.ReactNode
  skills: any[]
  selectedSkills: string[]
  onSkillsChange: (skills: string[]) => void
  description?: string
}) => {
  const content = (
    <div style={{ width: '320px' }}>
      <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>
  )

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

export const ProjectCreateEnhanced = () => {
  const navigate = useNavigate()
  const createProject = useProjectStore(state => state.createProject)
  const { skills, fetchSkills, loading: skillsLoading, error: skillsError } = useSkillStore()

  const [currentStep, setCurrentStep] = useState(0)
  const [loading, setLoading] = useState(false)
  const [aiGeneratingCharacters, setAiGeneratingCharacters] = useState(false)
  const [aiGeneratingOutline, setAiGeneratingOutline] = useState(false)
  const [aiGeneratingWorldSetting, setAiGeneratingWorldSetting] = useState(false)
  const [aiAnalyzingScript, setAiAnalyzingScript] = useState(false)
  const [aiAnalyzingWorldFromScript, setAiAnalyzingWorldFromScript] = useState(false)

  // 一键生成相关状态
  const [isGeneratingAll, setIsGeneratingAll] = useState(false)
  const [hasGeneratedAll, setHasGeneratedAll] = useState(false)
  const [generateProgress, setGenerateProgress] = useState({
    current: 0,
    total: 3,
    currentStep: ''
  })

  const [form] = Form.useForm()

  // 创作模式: 'upload' | 'create' | null
  const [creationMode, setCreationMode] = useState<'upload' | 'create' | null>(null)

  // 从头创作的子模式: 'text' | 'file' | null
  const [createSubMode, setCreateSubMode] = useState<'text' | 'file' | null>(null)

  // 上传的剧本内容
  const [uploadedScript, setUploadedScript] = useState('')

  // 直接输入的创作文字
  const [directTextInput, setDirectTextInput] = useState('')

  // 上传的灵感文件
  const [inspirationFile, setInspirationFile] = useState<any>(null)
  const [inspirationFileType, setInspirationFileType] = useState<'story' | 'character' | 'scene' | 'dialogue'>('story')

  // 剧本预览展开状态
  const [scriptExpanded, setScriptExpanded] = useState(false)

  // 每个 AI 功能独立配置的 Skills
  const [characterSkills, setCharacterSkills] = useState<string[]>([])
  const [outlineSkills, setOutlineSkills] = useState<string[]>([])
  const [worldSkills, setWorldSkills] = useState<string[]>([])
  const [analyzeSkills, setAnalyzeSkills] = useState<string[]>([])

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

  // AI 辅助生成的内容
  const [aiGeneratedContent, setAiGeneratedContent] = useState<any>({
    characters: '',
    outline: ''
  })

  // 项目级别的 Skills（用于后续创作流程）
  const [projectSkills, setProjectSkills] = useState<string[]>(['dialogue_writer_ancient', 'consistency_checker'])

  // 异步任务状态
  const [currentTaskId, setCurrentTaskId] = useState<string | null>(null)
  const [taskType, setTaskType] = useState<string>('')

  useEffect(() => {
    const loadSkills = async () => {
      try {
        console.log('正在加载 Skills...')
        await fetchSkills()
        console.log('Skills 加载完成:', skills.length)
      } catch (error) {
        console.error('加载 Skills 失败:', error)
        message.warning('Skills 加载失败，部分功能可能不可用')
      }
    }

    loadSkills()
  }, [])

  const steps = [
    {
      title: '选择创作方式',
      description: '选择从头创作或上传剧本',
      icon: <FileTextOutlined />
    },
    {
      title: 'AI 辅助完善',
      description: '让 AI 帮助生成大纲和人物',
      icon: <RobotOutlined />
    },
    {
      title: '确认创建',
      description: '确认所有配置并创建项目',
      icon: <CheckCircleOutlined />
    }
  ]

  // 上传剧本
  const handleUpload = (file: any) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      setUploadedScript(e.target?.result as string || '')
      setCreationMode('upload')
      message.success('剧本上传成功！')
    }
    reader.readAsText(file)
    return false // 阻止自动上传
  }

  // 选择从头创作的子模式
  const handleSelectCreateSubMode = (mode: 'text' | 'file') => {
    setCreateSubMode(mode)
    // 切换子模式时保留已有内容，但清空另一种模式的内容
    if (mode === 'text') {
      setInspirationFile(null)
    } else {
      setDirectTextInput('')
    }
  }

  // 清除创作方式选择（取消所有选择）
  const handleClearCreationMode = () => {
    setCreationMode(null)
    setCreateSubMode(null)
    setUploadedScript('')
    setDirectTextInput('')
    setInspirationFile(null)
  }

  // 处理灵感文件上传
  const handleInspirationUpload = (file: any) => {
    setInspirationFile(file)
    message.success('灵感文件已选择')
    return false // 阻止自动上传
  }

  // 验证步骤1并进入下一步
  const handleNextToStep1 = async () => {
    try {
      // 使用 validateFields 确保表单值正确验证
      const values = await form.validateFields(['name'])

      // 验证项目名称必填（无论哪种模式都需要项目名称）
      const name = values.name
      if (!name || name.trim() === '') {
        message.error('请填写项目名称')
        return
      }

      // 验证是否选择了创作方式
      if (!creationMode) {
        message.error('请选择创作方式（上传剧本或从头创作）')
        return
      }

      // 如果是上传剧本模式，验证已上传剧本
      if (creationMode === 'upload' && !uploadedScript) {
        message.error('请先上传剧本文件')
        return
      }

      // 如果是从头创作模式，验证子模式输入
      if (creationMode === 'create') {
        if (!createSubMode) {
          message.error('请选择输入方式（直接输入文字或上传灵感文件）')
          return
        }
        if (createSubMode === 'text' && !directTextInput.trim()) {
          message.error('请输入创作文字内容')
          return
        }
        if (createSubMode === 'file' && !inspirationFile) {
          message.error('请上传灵感文件')
          return
        }
      }

      setCurrentStep(1)
    } catch (error) {
      // 表单验证失败
      console.log('表单验证失败:', error)
    }
  }

  // AI 生成人物设定
  const handleAIGenerateCharacters = async () => {
    // 防止连续触发
    if (aiGeneratingCharacters) return

    setAiGeneratingCharacters(true)
    message.loading('AI 正在生成人物设定...', 0)

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

      const idea = `项目名称：${projectName}，总集数：${totalEpisodes}集，古风权谋剧题材`

      // 调用异步任务API
      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
      })

      // 设置任务ID和类型，用于后续查询结果
      setCurrentTaskId(response.taskId)
      setTaskType('generate_characters')

      // 轮询任务结果
      let attempts = 0
      const maxAttempts = 60 // 最多等待60秒

      const pollResult = async (): Promise<any> => {
        attempts++

        try {
          const result = await api.get(`/tasks/${response.taskId}`)

          if (result.status === 'completed') {
            return result.result
          } else if (result.status === 'failed') {
            throw new Error(result.error || '任务执行失败')
          } else if (attempts >= maxAttempts) {
            throw new Error('任务执行超时')
          } else {
            // 继续轮询
            await new Promise(resolve => setTimeout(resolve, 1000))
            return pollResult()
          }
        } catch (error: any) {
          throw error
        }
      }

      const result = await pollResult()

      // 处理结果
      let characterText = ''

      if (Array.isArray(result?.characters)) {
        characterText = result.characters.map((c: any) => {
          if (typeof c === 'string') return c
          if (c.name) {
            return c.lines ? `【${c.name}】出场 ${c.lines} 次` : `【${c.name}】`
          }
          return JSON.stringify(c)
        }).join('\n')
      } else if (typeof result?.characters === 'string') {
        characterText = result.characters
      } else if (typeof result === 'string') {
        characterText = result
      } else if (Array.isArray(result)) {
        characterText = result.map((c: any) => {
          if (typeof c === 'string') return c
          if (c.name) {
            return c.lines ? `【${c.name}】出场 ${c.lines} 次` : `【${c.name}】`
          }
          return JSON.stringify(c)
        }).join('\n')
      }

      if (characterText) {
        setAiGeneratedContent((prev: any) => ({ ...prev, characters: characterText }))
        form.setFieldsValue({ characters: characterText })

        // 关闭loading并显示成功提示
        message.destroy()
        message.success('人物设定生成完成！', 1.5)
      } else {
        message.destroy()
        message.warning('生成完成，但未返回有效内容')
      }
    } catch (error: any) {
      console.error('AI 生成人物设定失败:', error)
      message.destroy()
      message.error(`生成失败: ${error.message || '未知错误'}`)
    } finally {
      setAiGeneratingCharacters(false)
    }
  }

  // AI 分析上传的剧本
  const handleAIAnalyzeScript = async () => {
    // 防止连续触发
    if (aiAnalyzingScript) return

    setAiAnalyzingScript(true)
    message.loading('AI 正在分析剧本...', 0)

    try {
      // 获取剧本分析配置的技能信息
      const selectedSkillsInfo = skills.filter(s => analyzeSkills.includes(s.id))

      const data = await api.post('/ai-assistant/parse/script', {
        content: uploadedScript,
        extractCharacters: true,
        extractOutline: true,
        skills: selectedSkillsInfo.map(s => ({
          id: s.id,
          name: s.name,
          behavior: s.behavior_guide
        })),
        customPrompt: analyzePrompt || undefined
      }) as any

      // 提取分析结果
      const characters = data?.characters || []
      const outline = data?.outline || ''
      const summary = data?.summary || ''

      // 将人物列表转换为文本
      let characterText = ''
      if (characters.length > 0) {
        characterText = characters.map((c: any) =>
          `【${c.name}】出场 ${c.lines} 次`
        ).join('\n')
      }

      // 更新表单字段
      if (characterText) {
        form.setFieldsValue({ characters: characterText })
        setAiGeneratedContent((prev: any) => ({ ...prev, characters: characterText }))
      }
      if (outline) {
        const outlineText = typeof outline === 'string' ? outline : JSON.stringify(outline, null, 2)
        form.setFieldsValue({ overallOutline: outlineText })
        setAiGeneratedContent((prev: any) => ({ ...prev, outline: outlineText }))
      }

      // 关闭loading并显示成功提示
      message.destroy()
      message.success(`AI 分析完成！${summary}`, 1.5)
    } catch (error: any) {
      console.error('AI 分析失败，完整错误:', error)
      message.destroy()
      message.error(`AI 分析失败: ${error.message || '未知错误'}`)
    } finally {
      setAiAnalyzingScript(false)
    }
  }

  // AI 从剧本分析世界观
  const handleAIAnalyzeWorldFromScript = async () => {
    // 防止连续触发
    if (aiAnalyzingWorldFromScript) return

    setAiAnalyzingWorldFromScript(true)
    message.loading('AI 正在分析世界观...', 0)

    try {
      // 获取世界观生成配置的技能信息
      const selectedSkillsInfo = skills.filter(s => worldSkills.includes(s.id))

      const projectName = form.getFieldValue('name') || '未命名项目'

      const data = await api.post('/ai-assistant/generate/world-from-script', {
        script: uploadedScript,
        projectName,
        skills: selectedSkillsInfo.map(s => ({
          id: s.id,
          name: s.name,
          behavior: s.behavior_guide
        })),
        customPrompt: worldPrompt || undefined
      }) as any

      const worldSetting = data?.worldSetting || data?.result || data?.content || ''

      if (!worldSetting) {
        message.destroy()
        message.error('AI 分析失败：未返回有效内容')
        return
      }

      // 更新表单字段
      form.setFieldsValue({ worldSetting })
      setAiGeneratedContent((prev: any) => ({ ...prev, worldSetting }))

      // 关闭loading并显示成功提示
      message.destroy()
      message.success('AI 世界观分析完成！', 1.5)
    } catch (error: any) {
      console.error('AI 世界观分析失败，完整错误:', error)
      message.destroy()
      message.error(`AI 分析失败: ${error.message || '未知错误'}`)
    } finally {
      setAiAnalyzingWorldFromScript(false)
    }
  }

  // AI 生成世界观
  const handleAIGenerateWorldSetting = async () => {
    // 防止连续触发
    if (aiGeneratingWorldSetting) return

    setAiGeneratingWorldSetting(true)
    message.loading('AI 正在生成世界观设定...', 0)

    try {
      const projectName = form.getFieldValue('name') || '未命名项目'
      const selectedSkillsInfo = skills.filter(s => worldSkills.includes(s.id))

      const idea = `${projectName}世界观设定，架空朝代，皇权与相权之争，边关战事`

      // 调用异步任务API
      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
      })

      // 设置任务ID和类型，用于后续查询结果
      setCurrentTaskId(response.taskId)
      setTaskType('generate_world')

      // 轮询任务结果
      let attempts = 0
      const maxAttempts = 60 // 最多等待60秒

      const pollResult = async (): Promise<any> => {
        attempts++

        try {
          const result = await api.get(`/tasks/${response.taskId}`)

          if (result.status === 'completed') {
            return result.result
          } else if (result.status === 'failed') {
            throw new Error(result.error || '任务执行失败')
          } else if (attempts >= maxAttempts) {
            throw new Error('任务执行超时')
          } else {
            // 继续轮询
            await new Promise(resolve => setTimeout(resolve, 1000))
            return pollResult()
          }
        } catch (error: any) {
          throw error
        }
      }

      const result = await pollResult()

      // 处理结果
      const worldSetting = result?.worldSetting || result
      const worldText = typeof worldSetting === 'string' ? worldSetting : JSON.stringify(worldSetting, null, 2)

      if (worldText) {
        setAiGeneratedContent((prev: any) => ({ ...prev, worldSetting: worldText }))
        form.setFieldsValue({ worldSetting: worldText })

        // 关闭loading并显示成功提示
        message.destroy()
        message.success('世界观设定生成完成！', 1.5)
      } else {
        message.destroy()
        message.warning('生成完成，但未返回有效内容')
      }
    } catch (error: any) {
      console.error('AI 生成世界观设定失败:', error)
      message.destroy()
      message.error(`生成失败: ${error.message || '未知错误'}`)
    } finally {
      setAiGeneratingWorldSetting(false)
    }
  }

  // AI 生成大纲
  const handleAIGenerateOutline = async () => {
    // 防止连续触发
    if (aiGeneratingOutline) return

    setAiGeneratingOutline(true)
    message.loading('AI 正在生成剧情大纲...', 0)

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

      const idea = `${projectName}，古风权谋剧，边关将军与丞相之女的爱情故事，宫廷斗争`

      // 调用异步任务API
      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
      })

      // 设置任务ID和类型，用于后续查询结果
      setCurrentTaskId(response.taskId)
      setTaskType('generate_outline')

      // 轮询任务结果
      let attempts = 0
      const maxAttempts = 60 // 最多等待60秒

      const pollResult = async (): Promise<any> => {
        attempts++

        try {
          const result = await api.get(`/tasks/${response.taskId}`)

          if (result.status === 'completed') {
            return result.result
          } else if (result.status === 'failed') {
            throw new Error(result.error || '任务执行失败')
          } else if (attempts >= maxAttempts) {
            throw new Error('任务执行超时')
          } else {
            // 继续轮询
            await new Promise(resolve => setTimeout(resolve, 1000))
            return pollResult()
          }
        } catch (error: any) {
          throw error
        }
      }

      const result = await pollResult()

      // 处理结果
      const outline = result?.outline || result
      const outlineText = typeof outline === 'string' ? outline : JSON.stringify(outline, null, 2)

      if (outlineText) {
        setAiGeneratedContent((prev: any) => ({ ...prev, outline: outlineText }))
        form.setFieldsValue({ overallOutline: outlineText })

        // 关闭loading并显示成功提示
        message.destroy()
        message.success('剧情大纲生成完成！', 1.5)
      } else {
        message.destroy()
        message.warning('生成完成，但未返回有效内容')
      }
    } catch (error: any) {
      console.error('AI 生成剧情大纲失败:', error)
      message.destroy()
      message.error(`生成失败: ${error.message || '未知错误'}`)
    } finally {
      setAiGeneratingOutline(false)
    }
  }

  // 一键生成所有内容
  const handleGenerateAll = async () => {
    setIsGeneratingAll(true)
    setHasGeneratedAll(false)

    try {
      const projectName = form.getFieldValue('name') || '未命名项目'
      const totalEpisodes = form.getFieldValue('totalEpisodes') || 30

      // 步骤1: 生成/分析世界观（仅从头创作模式）
      if (!uploadedScript) {
        setGenerateProgress({ current: 1, total: 3, currentStep: '正在生成世界观设定...' })
        await new Promise(resolve => setTimeout(resolve, 100)) // 让UI更新

        try {
          // 使用默认技能
          const defaultWorldSkills = skills.filter(s => DEFAULT_SKILLS.worldSetting.includes(s.id))
          const idea = `${projectName}世界观设定，架空朝代，皇权与相权之争，边关战事`

          const data = await api.post('/ai-assistant/generate/world', {
            idea,
            projectName,
            genre: '古风',
            skills: defaultWorldSkills.map(s => ({
              id: s.id,
              name: s.name,
              behavior: s.behavior_guide
            }))
          }) as any

          const worldSetting = data?.worldSetting || data?.result || data?.content || ''
          if (worldSetting) {
            const worldText = typeof worldSetting === 'string' ? worldSetting : JSON.stringify(worldSetting, null, 2)
            form.setFieldsValue({ worldSetting: worldText })
            setAiGeneratedContent((prev: any) => ({ ...prev, worldSetting: worldText }))
          }
        } catch (error) {
          console.error('生成世界观失败:', error)
          message.warning('世界观生成失败，继续下一步...')
        }
      }

      // 步骤2: 生成/分析人物设定
      setGenerateProgress({ current: 2, total: 3, currentStep: uploadedScript ? '正在分析剧本中的人物...' : '正在生成人物设定...' })
      await new Promise(resolve => setTimeout(resolve, 100))

      try {
        const defaultCharacterSkills = skills.filter(s => DEFAULT_SKILLS.characters.includes(s.id))

        if (uploadedScript) {
          // 上传剧本模式：分析剧本
          const data = await api.post('/ai-assistant/parse/script', {
            content: uploadedScript,
            extractCharacters: true,
            extractOutline: false,
            skills: defaultCharacterSkills.map(s => ({
              id: s.id,
              name: s.name,
              behavior: s.behavior_guide
            }))
          }) as any

          const characters = data?.characters || []
          if (characters.length > 0) {
            const characterText = characters.map((c: any) =>
              `【${c.name}】出场 ${c.lines} 次`
            ).join('\n')
            form.setFieldsValue({ characters: characterText })
            setAiGeneratedContent((prev: any) => ({ ...prev, characters: characterText }))
          }
        } else {
          // 从头创作模式：生成人物
          const idea = `项目名称：${projectName}，总集数：${totalEpisodes}集，古风权谋剧题材`
          const data = await api.post('/ai-assistant/generate/characters', {
            idea,
            projectName,
            totalEpisodes,
            skills: defaultCharacterSkills.map(s => ({
              id: s.id,
              name: s.name,
              behavior: s.behavior_guide
            }))
          }) as any

          const characters = data?.characters || data?.result || data?.content || ''
          if (characters) {
            let characterText = ''
            if (typeof characters === 'string') {
              characterText = characters
            } else if (Array.isArray(characters)) {
              characterText = characters.map((c: any) => {
                if (typeof c === 'string') return c
                if (c.name) {
                  return c.lines ? `【${c.name}】出场 ${c.lines} 次` : `【${c.name}】`
                }
                return JSON.stringify(c)
              }).join('\n')
            } else {
              characterText = JSON.stringify(characters, null, 2)
            }
            form.setFieldsValue({ characters: characterText })
            setAiGeneratedContent((prev: any) => ({ ...prev, characters: characterText }))
          }
        }
      } catch (error) {
        console.error('生成/分析人物失败:', error)
        message.warning('人物生成失败，继续下一步...')
      }

      // 步骤3: 生成/分析大纲
      setGenerateProgress({ current: 3, total: 3, currentStep: uploadedScript ? '正在分析剧本大纲...' : '正在生成整体大纲...' })
      await new Promise(resolve => setTimeout(resolve, 100))

      try {
        const defaultOutlineSkills = skills.filter(s => DEFAULT_SKILLS.outline.includes(s.id))

        if (uploadedScript) {
          // 上传剧本模式：分析剧本
          const data = await api.post('/ai-assistant/parse/script', {
            content: uploadedScript,
            extractCharacters: false,
            extractOutline: true,
            skills: defaultOutlineSkills.map(s => ({
              id: s.id,
              name: s.name,
              behavior: s.behavior_guide
            }))
          }) as any

          const outline = data?.outline || data?.analysis || ''
          if (outline) {
            const outlineText = typeof outline === 'string' ? outline : JSON.stringify(outline, null, 2)
            form.setFieldsValue({ overallOutline: outlineText })
            setAiGeneratedContent((prev: any) => ({ ...prev, outline: outlineText }))
          }
        } else {
          // 从头创作模式：生成大纲
          const idea = `${projectName}，古风权谋剧，边关将军与丞相之女的爱情故事，宫廷斗争`
          const data = await api.post('/ai-assistant/generate/outline', {
            idea,
            totalEpisodes,
            genre: '古风',
            projectName,
            skills: defaultOutlineSkills.map(s => ({
              id: s.id,
              name: s.name,
              behavior: s.behavior_guide
            }))
          }) as any

          const outline = data?.outline || data?.result || data?.content || ''
          if (outline) {
            const outlineText = typeof outline === 'string' ? outline : JSON.stringify(outline, null, 2)
            form.setFieldsValue({ overallOutline: outlineText })
            setAiGeneratedContent((prev: any) => ({ ...prev, outline: outlineText }))
          }
        }
      } catch (error) {
        console.error('生成/分析大纲失败:', error)
        message.warning('大纲生成失败')
      }

      setHasGeneratedAll(true)
      message.success('一键生成完成！您可以手动调整各模块内容，或单独重新生成某模块。')
    } catch (error: any) {
      console.error('一键生成失败:', error)
      message.error(`一键生成失败: ${error.message || '未知错误'}`)
    } finally {
      setIsGeneratingAll(false)
      setGenerateProgress({ current: 0, total: 3, currentStep: '' })
    }
  }

  // 从步骤1快捷生成
  const handleQuickGenerateAll = async () => {
    setCurrentStep(1)
    // 等待步骤渲染
    setTimeout(() => {
      handleGenerateAll()
    }, 300)
  }

  const handleSubmit = async (values: any) => {
    try {
      // 确保表单通过验证
      await form.validateFields()
    } catch (error) {
      message.error('请检查表单填写是否完整')
      setCurrentStep(0)
      return
    }

    setLoading(true)
    try {
      console.log('表单提交值:', values)

      // 构建三级 Skills 配置
      const defaultTaskSkills: any[] = []

      // 添加对话创作配置
      if (projectSkills.length > 0) {
        const dialogueSkills = projectSkills.filter(id =>
          id.includes('dialogue') || id.includes('writer')
        )
        if (dialogueSkills.length > 0) {
          defaultTaskSkills.push({
            taskType: 'dialogue',
            skills: dialogueSkills.map(id => ({
              skill_id: id,
              enabled: true,
              priority: 10,
              parameter_overrides: {}
            }))
          })
        }

        // 添加审核配置
        const reviewSkills = projectSkills.filter(id =>
          id.includes('consistency') || id.includes('review') || id.includes('check')
        )
        if (reviewSkills.length > 0) {
          defaultTaskSkills.push({
            taskType: 'review',
            skills: reviewSkills.map(id => ({
              skill_id: id,
              enabled: true,
              priority: 10,
              parameter_overrides: {}
            }))
          })
        }
      }

      // 处理灵感内容（如果是文件上传，需要读取内容）
      let inspirationContent = directTextInput || ''
      if (createSubMode === 'file' && inspirationFile) {
        // 灵感文件内容已经在 handleInspirationUpload 中读取
        // 这里使用 originFileObj 来读取
        const reader = new FileReader()
        const fileContent = await new Promise<string>((resolve) => {
          reader.onload = (e) => resolve(e.target?.result as string || '')
          reader.readAsText(inspirationFile.originFileObj || inspirationFile)
        })
        inspirationContent = fileContent
      }

      const projectData: ProjectCreateRequest = {
        name: values.name,
        totalEpisodes: values.totalEpisodes || 30,
        globalContext: {
          worldSetting: values.worldSetting || '',
          overallOutline: values.overallOutline || '',
          // 保存创作内容
          uploadedScript: uploadedScript || '',  // 上传的剧本
          inspiration: inspirationContent,          // 灵感内容（直接输入或文件）
          styleGuide: values.characters || '',      // 人物设定
          characterProfiles: {},
          sceneSettings: {}
        },
        // 三级配置
        defaultTaskSkills,
        episodeSkillOverrides: {},
        // 保留兼容
        skillSettings: {}
      }

      console.log('项目创建数据:', projectData)

      const project = await createProject(projectData)

      message.success('项目创建成功！即将跳转到项目详情...')
      setTimeout(() => {
        navigate(`/projects/${project.id}`)
      }, 1000)
    } catch (error) {
      message.error(`创建失败: ${(error as Error).message}`)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div style={{ padding: '24px', maxWidth: '1000px', margin: '0 auto' }}>
      {/* Skills 加载状态 */}
      {skillsError && (
        <Alert
          message="Skills 加载失败"
          description={skillsError}
          type="warning"
          showIcon
          closable
          style={{ marginBottom: '16px' }}
        />
      )}

      <Card title="创建新的剧集项目 - AI 辅助模式" loading={skillsLoading}>
        <Steps current={currentStep} style={{ marginBottom: '24px' }}>
          {steps.map((step, i) => (
            <Step key={i} title={step.title} description={step.description} icon={step.icon} />
          ))}
        </Steps>

        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          {/* 步骤 1: 项目信息 + 创作方式 */}
          {currentStep === 0 && (
            <Space direction="vertical" size="large" style={{ width: '100%' }}>
              <Alert
                message="创建你的剧集项目"
                description="首先填写项目基础信息，然后选择创作方式"
                type="info"
                showIcon
              />

              {/* 项目基础信息 */}
              <Card title="项目基础信息" extra={<FileTextOutlined />}>
                <Form.Item name="name" label="项目名称" rules={[{ required: true, message: '请填写项目名称' }]}>
                  <Input placeholder="例如：宫廷风云" />
                </Form.Item>
                <Form.Item name="totalEpisodes" label="总集数" initialValue={30}>
                  <InputNumber min={1} max={100} style={{ width: '100%' }} />
                </Form.Item>
              </Card>

              {/* 创作方式选择 */}
              <Card title="选择创作方式" extra={<SettingOutlined />}>
                <Radio.Group
                  value={creationMode}
                  onChange={(e) => {
                    const mode = e.target.value
                    setCreationMode(mode)
                    // 切换模式时清空相关状态
                    if (mode === 'upload') {
                      setCreateSubMode(null)
                      setDirectTextInput('')
                      setInspirationFile(null)
                    } else if (mode === 'create') {
                      setUploadedScript('')
                    }
                  }}
                  style={{ width: '100%' }}
                >
                  <Space direction="vertical" style={{ width: '100%' }} size="middle">
                    {/* 上传剧本选项 */}
                    <Radio value="upload">
                      <Card
                        size="small"
                        style={{
                          width: '100%',
                          border: creationMode === 'upload' ? '2px solid #1677ff' : '1px solid #d9d9d9',
                          backgroundColor: creationMode === 'upload' ? '#f0f5ff' : undefined
                        }}
                      >
                        <Space direction="vertical" style={{ width: '100%' }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                            <UploadOutlined style={{ fontSize: '20px', color: '#1677ff' }} />
                            <span style={{ fontWeight: 500 }}>上传完整剧本</span>
                          </div>
                          <p style={{ margin: '8px 0', color: '#666' }}>
                            上传已有剧本，AI 将分析提取人物、世界观和剧情大纲
                          </p>

                          {creationMode === 'upload' && (
                            <>
                              <Upload.Dragger
                                name="script"
                                multiple={false}
                                accept=".txt,.md,.docx"
                                showUploadList={false}
                                beforeUpload={handleUpload}
                                style={{ padding: '20px' }}
                              >
                                <p className="ant-upload-drag-icon">
                                  <UploadOutlined style={{ fontSize: '32px', color: '#1677ff' }} />
                                </p>
                                <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
                                <p className="ant-upload-hint">支持 .txt, .md, .docx 格式的剧本</p>
                              </Upload.Dragger>

                              {uploadedScript && (
                                <div style={{ marginTop: '12px' }}>
                                  <Tag color="success" icon={<CheckCircleOutlined />}>
                                    已上传 ({uploadedScript.length} 字符)
                                  </Tag>
                                  <Button
                                    type="link"
                                    size="small"
                                    onClick={(e) => {
                                      e.stopPropagation()
                                      setUploadedScript('')
                                    }}
                                    style={{ marginLeft: '8px' }}
                                  >
                                    重新上传
                                  </Button>
                                </div>
                              )}

                              {/* 剧本内容预览 */}
                              {uploadedScript && (
                                <>
                                  <Divider style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                    <span>剧本预览</span>
                                    {uploadedScript.length > 500 && (
                                      <Button
                                        type="link"
                                        size="small"
                                        onClick={(e) => {
                                          e.stopPropagation()
                                          setScriptExpanded(!scriptExpanded)
                                        }}
                                        style={{ padding: 0, height: 'auto' }}
                                      >
                                        {scriptExpanded ? '收起' : '展开全部'}
                                      </Button>
                                    )}
                                  </Divider>
                                  <div
                                    style={{
                                      maxHeight: scriptExpanded ? '60vh' : '150px',
                                      overflowY: 'auto',
                                      background: '#f5f5f5',
                                      padding: '12px',
                                      borderRadius: '4px',
                                      fontSize: '12px',
                                      whiteSpace: 'pre-wrap',
                                      wordBreak: 'break-word',
                                      border: '1px solid #d9d9d9',
                                      lineHeight: '1.6'
                                    }}
                                  >
                                    {uploadedScript}
                                  </div>
                                  {!scriptExpanded && uploadedScript.length > 500 && (
                                    <div style={{ marginTop: '8px', textAlign: 'center' }}>
                                      <Button
                                        type="link"
                                        size="small"
                                        onClick={(e) => {
                                          e.stopPropagation()
                                          setScriptExpanded(true)
                                        }}
                                      >
                                        查看完整剧本 ({uploadedScript.length} 字符)
                                      </Button>
                                    </div>
                                  )}
                                </>
                              )}
                            </>
                          )}
                        </Space>
                      </Card>
                    </Radio>

                    {/* 从头创作选项 */}
                    <Radio value="create">
                      <Card
                        size="small"
                        style={{
                          width: '100%',
                          border: creationMode === 'create' ? '2px solid #1677ff' : '1px solid #d9d9d9',
                          backgroundColor: creationMode === 'create' ? '#f0f5ff' : undefined
                        }}
                      >
                        <Space direction="vertical" style={{ width: '100%' }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                            <EditOutlined style={{ fontSize: '20px', color: '#1677ff' }} />
                            <span style={{ fontWeight: 500 }}>从头创作</span>
                          </div>
                          <p style={{ margin: '8px 0', color: '#666' }}>
                            让 AI 根据你的创意完整生成人物设定和剧情大纲
                          </p>

                          {creationMode === 'create' && (
                            <>
                              <Divider style={{ margin: '12px 0' }} />

                              {/* 子模式选择 */}
                              <div>
                                <div style={{ marginBottom: '8px', fontSize: '14px', fontWeight: 500 }}>
                                  选择输入方式：
                                </div>
                                <Radio.Group
                                  value={createSubMode}
                                  onChange={(e) => handleSelectCreateSubMode(e.target.value)}
                                  style={{ width: '100%' }}
                                >
                                  <Space direction="vertical" style={{ width: '100%' }}>
                                    <Radio value="text">
                                      <Space>
                                        <EditOutlined />
                                        <span>直接输入创作文字</span>
                                      </Space>
                                    </Radio>
                                    <Radio value="file">
                                      <Space>
                                        <UploadOutlined />
                                        <span>上传灵感文件</span>
                                      </Space>
                                    </Radio>
                                  </Space>
                                </Radio.Group>
                              </div>

                              {/* 直接输入文字 */}
                              {createSubMode === 'text' && (
                                <div style={{ marginTop: '12px' }}>
                                  <TextArea
                                    value={directTextInput}
                                    onChange={(e) => setDirectTextInput(e.target.value)}
                                    placeholder="请输入您的创作文字、故事大纲、角色设定等内容..."
                                    rows={6}
                                    maxLength={10000}
                                    showCount
                                  />
                                  {directTextInput && (
                                    <div style={{ marginTop: '8px' }}>
                                      <Tag color="success" icon={<CheckCircleOutlined />}>
                                        已输入 {directTextInput.length} 个字符
                                      </Tag>
                                    </div>
                                  )}
                                </div>
                              )}

                              {/* 上传灵感文件 */}
                              {createSubMode === 'file' && (
                                <div style={{ marginTop: '12px' }}>
                                  <div style={{ marginBottom: '8px' }}>
                                    <span style={{ fontSize: '14px', fontWeight: 500 }}>灵感类型：</span>
                                    <Select
                                      value={inspirationFileType}
                                      onChange={setInspirationFileType}
                                      style={{ width: '200px', marginLeft: '8px' }}
                                    >
                                      <Select.Option value="story">故事灵感</Select.Option>
                                      <Select.Option value="character">角色设定</Select.Option>
                                      <Select.Option value="scene">场景描述</Select.Option>
                                      <Select.Option value="dialogue">对话片段</Select.Option>
                                    </Select>
                                  </div>
                                  <Upload
                                    accept=".txt,.md,.doc,.docx"
                                    maxCount={1}
                                    fileList={inspirationFile ? [inspirationFile] : []}
                                    beforeUpload={handleInspirationUpload}
                                    onRemove={() => setInspirationFile(null)}
                                  >
                                    <Button icon={<UploadOutlined />} disabled={inspirationFile !== null}>
                                      {inspirationFile ? '已选择文件' : '选择文件（支持 .txt, .md, .doc, .docx）'}
                                    </Button>
                                  </Upload>
                                  {inspirationFile && (
                                    <div style={{ marginTop: '8px', fontSize: '12px', color: '#52c41a' }}>
                                      ✓ 已选择: {inspirationFile.name}
                                    </div>
                                  )}
                                </div>
                              )}

                              {createSubMode && (
                                <Tag color="blue">
                                  {createSubMode === 'text' && '已选择：直接输入'}
                                  {createSubMode === 'file' && '已选择：文件上传'}
                                </Tag>
                              )}
                            </>
                          )}
                        </Space>
                      </Card>
                    </Radio>
                  </Space>
                </Radio.Group>

                {/* 已选择提示 */}
                {creationMode && (
                  <Alert
                    message={
                      creationMode === 'upload'
                        ? '已选择：上传剧本模式'
                        : creationMode === 'create' && createSubMode === 'text'
                          ? '已选择：从头创作 - 直接输入文字'
                          : creationMode === 'create' && createSubMode === 'file'
                            ? '已选择：从头创作 - 上传灵感文件'
                            : '已选择：从头创作模式'
                    }
                    description={
                      creationMode === 'upload' && uploadedScript
                        ? `已上传剧本 (${uploadedScript.length} 字符)`
                        : creationMode === 'create' && createSubMode === 'text' && directTextInput
                          ? `已输入 ${directTextInput.length} 个字符`
                          : creationMode === 'create' && createSubMode === 'file' && inspirationFile
                            ? `已上传文件: ${inspirationFile.name}`
                            : creationMode === 'create' && !createSubMode
                              ? '请选择输入方式'
                              : undefined
                    }
                    type="success"
                    showIcon
                    action={
                      <Button size="small" type="link" onClick={handleClearCreationMode}>
                        重新选择
                      </Button>
                    }
                  />
                )}
              </Card>

              {/* 快捷操作：选择创作方式后显示 */}
              {creationMode && (
                <Card
                  title="快捷操作"
                  style={{ marginTop: '16px', background: 'linear-gradient(135deg, #f0f5ff 0%, #e6f7ff 100%)' }}
                  extra={<ThunderboltOutlined style={{ color: '#1677ff' }} />}
                >
                  <Space direction="vertical" style={{ width: '100%' }}>
                    <Alert
                      message="选择你的下一步操作"
                      description={
                        creationMode === 'upload'
                          ? "可以立即让AI分析剧本并提取所有信息，或进入下一步手动配置每个模块"
                          : creationMode === 'create' && createSubMode
                            ? "可以立即让AI根据你的输入生成所有创作内容，或进入下一步手动配置每个模块"
                            : "请先完成输入方式选择和内容填写"
                      }
                      type="info"
                      showIcon
                    />
                    <Space style={{ width: '100%', justifyContent: 'center' }}>
                      <Button
                        type="primary"
                        size="large"
                        icon={<ThunderboltOutlined />}
                        onClick={handleQuickGenerateAll}
                        disabled={creationMode === 'create' && !createSubMode}
                      >
                        立即AI生成所有内容
                      </Button>
                      <Button
                        size="large"
                        onClick={handleNextToStep1}
                        disabled={creationMode === 'create' && !createSubMode}
                      >
                        进入下一步手动配置
                      </Button>
                    </Space>
                  </Space>
                </Card>
              )}

              {/* 统一的下一步按钮 */}
              <div style={{ textAlign: 'right', marginTop: '16px' }}>
                <Button
                  type="primary"
                  size="large"
                  icon={<ArrowRightOutlined />}
                  onClick={handleNextToStep1}
                >
                  下一步：AI 辅助
                </Button>
              </div>
            </Space>
          )}

          {/* 步骤 2: AI 辅助完善 */}
          {currentStep === 1 && (
            <Space direction="vertical" size="large" style={{ width: '100%' }}>
              {/* 一键生成区域 */}
              {!hasGeneratedAll && !isGeneratingAll && (
                <Card
                  title="一键生成所有内容"
                  style={{ background: 'linear-gradient(135deg, #f0f5ff 0%, #e6f7ff 100%)' }}
                  extra={<ThunderboltOutlined style={{ color: '#1677ff' }} />}
                >
                  <Space direction="vertical" style={{ width: '100%' }}>
                    <Alert
                      message="使用默认Skill配置依次生成所有内容"
                      description={uploadedScript
                        ? "将依次分析：剧本提取人物 → 分析世界观 → 分析剧本大纲"
                        : "将依次生成：世界观设定 → 人物设定 → 整体大纲"}
                      type="info"
                      showIcon
                    />
                    <Button
                      type="primary"
                      size="large"
                      icon={<ThunderboltOutlined />}
                      onClick={handleGenerateAll}
                      style={{ width: '100%' }}
                    >
                      一键生成所有内容
                    </Button>
                  </Space>
                </Card>
              )}

              {/* 生成进度显示 */}
              {isGeneratingAll && (
                <Card
                  title="AI 生成中..."
                  style={{ background: '#f0f5ff' }}
                >
                  <Space direction="vertical" style={{ width: '100%' }}>
                    <Progress
                      percent={Math.round((generateProgress.current / generateProgress.total) * 100)}
                      status="active"
                      strokeColor={{
                        '0%': '#108ee9',
                        '100%': '#87d068',
                      }}
                    />
                    <div style={{ textAlign: 'center', color: '#666' }}>
                      {generateProgress.currentStep}
                    </div>
                  </Space>
                </Card>
              )}

              <Alert
                message={uploadedScript ? "AI 将分析你的剧本，提取人物和大纲" : "AI 将根据你的创意生成完整的大纲和人物"}
                description="你也可以手动输入或修改 AI 生成的内容。点击「配置」可以为每个 AI 生成任务选择不同的技能。"
                type="info"
                showIcon
              />

              {uploadedScript ? (
                // 上传剧本模式：显示 AI 分析功能
                <>
                  <Card
                    title="AI 分析剧本"
                    extra={
                      <Space>
                        <SkillSelectorWithPrompt
                          title="配置剧本分析"
                          icon={<SettingOutlined />}
                          skills={skills}
                          selectedSkills={analyzeSkills}
                          onSkillsChange={setAnalyzeSkills}
                          customPrompt={analyzePrompt}
                          onPromptChange={setAnalyzePrompt}
                          description="选择用于剧本分析的技能，会影响提取效果"
                        />
                        <Button
                          type="primary"
                          icon={<RobotOutlined />}
                          loading={aiAnalyzingScript}
                          onClick={handleAIAnalyzeScript}
                        >
                          {aiAnalyzingScript ? '分析中...' : (form.getFieldValue('characters') ? 'AI 重新分析' : 'AI 分析')}
                        </Button>
                      </Space>
                    }
                  >
                    <Form.Item name="characters" label="提取的人物 (可选)">
                      <TextArea
                        rows={6}
                        placeholder="AI 将自动分析剧本中的人物..."
                      />
                    </Form.Item>
                  </Card>

                  <Card
                    title="AI 分析世界观"
                    extra={
                      <Space>
                        <SkillSelectorWithPrompt
                          title="配置世界观分析"
                          icon={<SettingOutlined />}
                          skills={skills}
                          selectedSkills={worldSkills}
                          onSkillsChange={setWorldSkills}
                          customPrompt={worldPrompt}
                          onPromptChange={setWorldPrompt}
                          description="选择用于世界观分析的技能，会影响设定风格"
                        />
                        <Button
                          type="primary"
                          icon={<RobotOutlined />}
                          loading={aiAnalyzingWorldFromScript}
                          onClick={handleAIAnalyzeWorldFromScript}
                        >
                          {aiAnalyzingWorldFromScript ? '分析中...' : (form.getFieldValue('worldSetting') ? 'AI 重新分析' : 'AI 分析')}
                        </Button>
                      </Space>
                    }
                  >
                    <Form.Item name="worldSetting" label="世界观设定 (可选)">
                      <TextArea
                        rows={6}
                        placeholder="AI 将从剧本中提取和分析世界观设定，如时代背景、地理环境、社会结构等..."
                      />
                    </Form.Item>
                  </Card>
                </>
              ) : (
                // 从头创作模式：显示 AI 生成人物设定
                <Card
                  title="AI 生成人物设定"
                  extra={
                    <Space>
                      <SkillSelectorWithPrompt
                        title="配置人物生成"
                        icon={<SettingOutlined />}
                        skills={skills}
                        selectedSkills={characterSkills}
                        onSkillsChange={setCharacterSkills}
                        customPrompt={characterPrompt}
                        onPromptChange={setCharacterPrompt}
                        description="选择用于生成人物设定的技能，会影响人物风格"
                      />
                      <Button
                        type="primary"
                        icon={<RobotOutlined />}
                        loading={aiGeneratingCharacters}
                        onClick={handleAIGenerateCharacters}
                      >
                        {aiGeneratingCharacters ? '生成中...' : (form.getFieldValue('characters') ? 'AI 重新生成' : 'AI 生成')}
                      </Button>
                    </Space>
                  }
                >
                  <Form.Item name="characters" label="人物设定 (可选)">
                    <TextArea
                      rows={6}
                      placeholder="让 AI 生成人物设定，或手动输入..."
                    />
                  </Form.Item>
                </Card>
              )}

              <Card
                title={uploadedScript ? "AI 分析剧本大纲" : "AI 生成整体大纲"}
                extra={
                  <Space>
                    <SkillSelectorWithPrompt
                      title="配置大纲生成"
                      icon={<SettingOutlined />}
                      skills={skills}
                      selectedSkills={outlineSkills}
                      onSkillsChange={setOutlineSkills}
                      customPrompt={outlinePrompt}
                      onPromptChange={setOutlinePrompt}
                      description="选择用于生成大纲的技能，会影响剧情结构"
                    />
                    <Button
                      type="primary"
                      icon={<RobotOutlined />}
                      loading={aiGeneratingOutline}
                      onClick={handleAIGenerateOutline}
                    >
                      {aiGeneratingOutline
                        ? (uploadedScript ? '分析中...' : '生成中...')
                        : (form.getFieldValue('overallOutline')
                          ? (uploadedScript ? 'AI 重新分析' : 'AI 重新生成')
                          : (uploadedScript ? 'AI 分析' : 'AI 生成'))}
                    </Button>
                  </Space>
                }
              >
                <Form.Item name="overallOutline" label="整体大纲 (可选)">
                  <TextArea
                    rows={8}
                    placeholder={uploadedScript ? "AI 将自动分析剧本的大纲结构..." : "让 AI 生成整体大纲，或手动输入..."}
                  />
                </Form.Item>
              </Card>

              {!uploadedScript && (
                <Card
                  title="世界观设定 (可选)"
                  extra={
                    <Space>
                      <SkillSelectorWithPrompt
                        title="配置世界观生成"
                        icon={<SettingOutlined />}
                        skills={skills}
                        selectedSkills={worldSkills}
                        onSkillsChange={setWorldSkills}
                        customPrompt={worldPrompt}
                        onPromptChange={setWorldPrompt}
                        description="选择用于生成世界观的技能，会影响设定风格"
                      />
                      <Button
                        type="primary"
                        icon={<RobotOutlined />}
                        loading={aiGeneratingWorldSetting}
                        onClick={handleAIGenerateWorldSetting}
                      >
                        {aiGeneratingWorldSetting ? '生成中...' : (form.getFieldValue('worldSetting') ? 'AI 重新生成' : 'AI 生成')}
                      </Button>
                    </Space>
                  }
                >
                  <Form.Item name="worldSetting">
                    <TextArea
                      rows={4}
                      placeholder="让 AI 生成世界观设定，或手动输入..."
                    />
                  </Form.Item>
                </Card>
              )}

              {/* 项目级别 Skills 配置 */}
              <Card
                title="项目创作技能 (用于后续创作流程)"
                extra={<SettingOutlined />}
              >
                <Alert
                  message="这些技能将在项目创建后，用于剧集创作等后续流程"
                  description="例如：对话创作、一致性检查等"
                  type="info"
                  showIcon
                  style={{ marginBottom: '16px' }}
                />
                <Select
                  mode="multiple"
                  style={{ width: '100%' }}
                  placeholder="选择项目级别的技能"
                  value={projectSkills}
                  onChange={setProjectSkills}
                  options={skills.map(skill => ({
                    value: skill.id,
                    label: skill.name
                  }))}
                />
                <div style={{ marginTop: '12px' }}>
                  <Space wrap>
                    {projectSkills.map(skillId => {
                      const skill = skills.find(s => s.id === skillId)
                      return skill ? (
                        <Tag
                          key={skillId}
                          color="blue"
                          closable
                          onClose={() => setProjectSkills(prev => prev.filter(id => id !== skillId))}
                        >
                          {skill.name}
                        </Tag>
                      ) : null
                    })}
                  </Space>
                </div>
              </Card>

              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '16px' }}>
                <Button onClick={() => setCurrentStep(0)}>
                  上一步
                </Button>
                <Button
                  type="primary"
                  size="large"
                  icon={<ArrowRightOutlined />}
                  onClick={() => setCurrentStep(2)}
                >
                  下一步：确认
                </Button>
              </div>
            </Space>
          )}

          {/* 步骤 3: 确认创建 */}
          {currentStep === 2 && (
            <Space direction="vertical" size="large" style={{ width: '100%' }}>
              <Alert
                message="确认所有配置信息"
                description="检查无误后即可创建项目"
                type="success"
                showIcon
              />

              <Card title="配置摘要">
                <Form.Item label="项目名称">
                  {form.getFieldValue('name') || '未填写'}
                </Form.Item>

                <Form.Item label="总集数">
                  {form.getFieldValue('totalEpisodes') || 30} 集
                </Form.Item>

                <Divider />

                <Form.Item label="人物设定">
                  <div style={{
                    background: '#f5f5f5',
                    padding: '12px',
                    borderRadius: '4px',
                    whiteSpace: 'pre-wrap',
                    maxHeight: '200px',
                    overflowY: 'auto'
                  }}>
                    {typeof aiGeneratedContent.characters === 'string'
                      ? aiGeneratedContent.characters
                      : aiGeneratedContent.characters
                        ? JSON.stringify(aiGeneratedContent.characters, null, 2)
                        : '未设置'}
                  </div>
                </Form.Item>

                <Form.Item label="整体大纲">
                  <div style={{
                    background: '#f5f5f5',
                    padding: '12px',
                    borderRadius: '4px',
                    whiteSpace: 'pre-wrap',
                    maxHeight: '200px',
                    overflowY: 'auto'
                  }}>
                    {typeof aiGeneratedContent.outline === 'string'
                      ? aiGeneratedContent.outline
                      : aiGeneratedContent.outline
                        ? JSON.stringify(aiGeneratedContent.outline, null, 2)
                        : '未设置'}
                  </div>
                </Form.Item>

                <Divider />

                <Form.Item label="项目创作技能">
                  <Space wrap>
                    {projectSkills.map(skillId => {
                      const skill = skills.find(s => s.id === skillId)
                      return skill ? (
                        <Tag key={skillId} color="blue">
                          {skill.name}
                        </Tag>
                      ) : null
                    })}
                  </Space>
                </Form.Item>
              </Card>

              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '16px' }}>
                <Button onClick={() => setCurrentStep(1)}>
                  返回修改
                </Button>
                <Button
                  type="primary"
                  size="large"
                  htmlType="submit"
                  loading={loading}
                >
                  {loading ? '创建中...' : '创建项目'}
                </Button>
              </div>
            </Space>
          )}
        </Form>
      </Card>
    </div>
  )
}
