/**
 * 单集 Skills 配置组件
 */
import { useState, useEffect } from 'react'
import { Modal, Select, Button, Space, Card, Checkbox, Divider, message } from 'antd'
import { SettingOutlined, SaveOutlined } from '@ant-design/icons'
import { projectService, TaskSkillConfig, SkillAssignment } from '@/services/projectService'
import { useSkillStore } from '@/stores/skillStore'

interface EpisodeSkillConfigProps {
  visible: boolean
  projectId: string
  episodeNumber: number
  currentConfig?: any
  onSave: (config: any) => void
  onClose: () => void
}

export const EpisodeSkillConfig: React.FC<EpisodeSkillConfigProps> = ({
  visible,
  projectId,
  episodeNumber,
  currentConfig,
  onSave,
  onClose
}) => {
  const { skills } = useSkillStore()
  const [loading, setLoading] = useState(false)
  const [useDefault, setUseDefault] = useState(true)

  // 对话创作 Skills
  const [dialogueSkills, setDialogueSkills] = useState<string[]>([])

  // 审核 Skills
  const [reviewSkills, setReviewSkills] = useState<string[]>([])

  // 大纲生成 Skills
  const [outlineSkills, setOutlineSkills] = useState<string[]>([])

  useEffect(() => {
    if (currentConfig && currentConfig.task_configs) {
      // 从现有配置加载
      const dialogueConfig = currentConfig.task_configs.find((c: any) => c.task_type === 'dialogue')
      if (dialogueConfig) {
        setDialogueSkills(dialogueConfig.skills.map((s: any) => s.skill_id))
      }

      const reviewConfig = currentConfig.task_configs.find((c: any) => c.task_type === 'review')
      if (reviewConfig) {
        setReviewSkills(reviewConfig.skills.map((s: any) => s.skill_id))
      }

      const outlineConfig = currentConfig.task_configs.find((c: any) => c.task_type === 'outline')
      if (outlineConfig) {
        setOutlineSkills(outlineConfig.skills.map((s: any) => s.skill_id))
      }

      setUseDefault(currentConfig.use_project_default ?? true)
    }
  }, [currentConfig])

  const handleSave = async () => {
    if (useDefault) {
      // 使用项目默认，删除单集配置
      await onDeleteConfig()
      return
    }

    setLoading(true)
    try {
      const taskConfigs: TaskSkillConfig[] = []

      // 对话创作配置
      if (dialogueSkills.length > 0) {
        taskConfigs.push({
          task_type: 'dialogue',
          skills: dialogueSkills.map(id => ({
            skill_id: id,
            enabled: true,
            priority: 10,
            parameter_overrides: {}
          }))
        })
      }

      // 审核配置
      if (reviewSkills.length > 0) {
        taskConfigs.push({
          task_type: 'review',
          skills: reviewSkills.map(id => ({
            skill_id: id,
            enabled: true,
            priority: 10,
            parameter_overrides: {}
          }))
        })
      }

      // 大纲配置
      if (outlineSkills.length > 0) {
        taskConfigs.push({
          task_type: 'outline',
          skills: outlineSkills.map(id => ({
            skill_id: id,
            enabled: true,
            priority: 10,
            parameter_overrides: {}
          }))
        })
      }

      const config = {
        episode_number: episodeNumber,
        use_project_default: false,
        task_configs: taskConfigs
      }

      // 调用 API 保存
      await projectService.updateProject(projectId, {
        episodeSkillOverrides: {
          [episodeNumber]: config
        }
      })

      message.success(`EP${episodeNumber} 的 Skills 配置已保存`)
      onSave(config)
      onClose()
    } catch (error) {
      message.error(`保存失败: ${(error as Error).message}`)
    } finally {
      setLoading(false)
    }
  }

  const onDeleteConfig = async () => {
    setLoading(true)
    try {
      // 删除单集配置（恢复使用项目默认）
      // 注意：这里需要调用删除 API，暂时用更新方式
      const currentOverrides = (await projectService.getProject(projectId)).episodeSkillOverrides || {}
      const newOverrides = { ...currentOverrides }
      delete newOverrides[episodeNumber]

      await projectService.updateProject(projectId, {
        episodeSkillOverrides: newOverrides
      })

      message.success(`EP${episode_number} 的配置已删除，将使用项目默认配置`)
      onSave(null)
      onClose()
    } catch (error) {
      message.error(`删除失败: ${(error as Error).message}`)
    } finally {
      setLoading(false)
    }
  }

  // 按任务类型过滤 Skills
  const getSkillsForTask = (taskType: string) => {
    if (taskType === 'dialogue') {
      return skills.filter(s =>
        s.id.includes('dialogue') ||
        s.id.includes('writer') ||
        s.category === '对话创作'
      )
    }
    if (taskType === 'review') {
      return skills.filter(s =>
        s.id.includes('consistency') ||
        s.id.includes('review') ||
        s.id.includes('check') ||
        s.category === '内容审核'
      )
    }
    if (taskType === 'outline') {
      return skills.filter(s =>
        s.id.includes('outline') ||
        s.category === '大纲生成'
      )
    }
    return skills
  }

  return (
    <Modal
      title={`配置第 ${episodeNumber} 集的 Skills`}
      open={visible}
      onOk={handleSave}
      onCancel={onClose}
      width={600}
      footer={[
        <Button key="cancel" onClick={onClose}>
          取消
        </Button>,
        <Button
          key="delete"
          danger={!useDefault}
          onClick={onDeleteConfig}
          disabled={useDefault}
        >
          恢复默认
        </Button>,
        <Button
          key="save"
          type="primary"
          icon={<SaveOutlined />}
          loading={loading}
          onClick={handleSave}
        >
          保存配置
        </Button>
      ]}
    >
      <Space direction="vertical" style={{ width: '100%' }} size="middle">
        <Card size="small">
          <Space>
            <Checkbox
              checked={useDefault}
              onChange={(e) => setUseDefault(e.target.checked)}
            >
              使用项目默认配置
            </Checkbox>
          </Space>
          {!useDefault && (
            <div style={{ marginTop: 8, color: '#999', fontSize: 12 }}>
              取消勾选后可以为本集单独配置 Skills
            </div>
          )}
        </Card>

        {!useDefault && (
          <>
            <Divider orientation="left">对话创作</Divider>
            <Select
              mode="multiple"
              style={{ width: '100%' }}
              placeholder="选择对话创作 Skills"
              value={dialogueSkills}
              onChange={setDialogueSkills}
              options={getSkillsForTask('dialogue').map(s => ({
                value: s.id,
                label: s.name
              }))}
            />
            <div style={{ marginTop: 8, color: '#999', fontSize: 12 }}>
              已选: {dialogueSkills.length} 个技能
            </div>

            <Divider orientation="left">内容审核</Divider>
            <Select
              mode="multiple"
              style={{ width: '100%' }}
              placeholder="选择审核 Skills"
              value={reviewSkills}
              onChange={setReviewSkills}
              options={getSkillsForTask('review').map(s => ({
                value: s.id,
                label: s.name
              }))}
            />
            <div style={{ marginTop: 8, color: '#999', fontSize: 12 }}>
              已选: {reviewSkills.length} 个技能
            </div>

            <Divider orientation="left">大纲生成</Divider>
            <Select
              mode="multiple"
              style={{ width: '100%' }}
              placeholder="选择大纲生成 Skills"
              value={outlineSkills}
              onChange={setOutlineSkills}
              options={getSkillsForTask('outline').map(s => ({
                value: s.id,
                label: s.name
              }))}
            />
            <div style={{ marginTop: 8, color: '#999', fontSize: 12 }}>
              已选: {outlineSkills.length} 个技能
            </div>
          </>
        )}

        {useDefault && (
          <Card size="small" style={{ background: '#f5f5f5' }}>
            <div style={{ color: '#999' }}>
              本集将使用项目默认配置的 Skills
            </div>
          </Card>
        )}
      </Space>
    </Modal>
  )
}

export default EpisodeSkillConfig
