import { useState, useEffect, useRef, useCallback } from 'react'
import { message } from 'antd'
import { getDigitalHumanList, submitVideo, getVideoTask } from '@/api/xiling'
import { digitalHumans as staticFigures, femaleVoices, maleVoices } from '@/common/wangeditor-customer/menu/common/digital-human-data'

/**
 * 数字人功能 Hook (简化版：仅文本驱动，移除底图)
 */
export default function useDigitalHuman() {
  const [figures, setFigures] = useState(staticFigures)
  const [loadingFigures, setLoadingFigures] = useState(false)
  const [isGenerating, setIsGenerating] = useState(false)
  const [generatedVideo, setGeneratedVideo] = useState(null)
  const [error, setError] = useState(null)
  
  const pollTimerRef = useRef(null)

  const stopPolling = useCallback(() => {
    if (pollTimerRef.current) {
      clearInterval(pollTimerRef.current)
      pollTimerRef.current = null
    }
  }, [])

  const startPolling = useCallback((taskId, figureName) => {
    stopPolling()
    pollTimerRef.current = setInterval(async () => {
      try {
        const response = await getVideoTask({ taskId })
        const { status, videoUrl } = response.result
        
        if (status === 'SUCCESS' && videoUrl) {
          stopPolling()
          setGeneratedVideo({
            url: videoUrl,
            taskId: taskId,
            figureName: figureName,
          })
          setIsGenerating(false)
          message.success('数字人视频生成成功！')
        } else if (status === 'FAILED') {
          stopPolling()
          setIsGenerating(false)
          setError(response.result.failedMessage || '生成失败')
          message.error(`视频生成失败: ${response.result.failedMessage || '未知错误'}`)
        }
      } catch (err) {
        console.error('Polling Error:', err)
      }
    }, 5000)
  }, [stopPolling])

  // 处理获取列表
  const fetchFigures = useCallback(async () => {
    setLoadingFigures(true)
    try {
      const list = await getDigitalHumanList({ systemFigure: true })
      if (list && list.length > 0) {
        setFigures(prev => {
          // 创建新数组，保留静态配置，并用 API 的数据补充或更新关键信息（如 avatar）
          const combined = [...prev]
          list.forEach(item => {
            const existingIndex = combined.findIndex(c => String(c.id) === String(item.figureId))
            const avatarUrl = item.figureImageUrl || item.figureVideoThumbnailUrl
            
            if (existingIndex > -1) {
              // 如果静态配置已存在，且 API 返回了有效的预览图，则更新它
              if (avatarUrl) {
                combined[existingIndex] = {
                  ...combined[existingIndex],
                  avatar: avatarUrl
                }
              }
            } else {
              // 如果是全新的数字人，则添加
              combined.push({
                id: item.figureId,
                name: item.name,
                avatar: avatarUrl,
              })
            }
          })
          return combined
        })
      }
    } catch (err) {
      console.error('Fetch Figures Error:', err)
    } finally {
      setLoadingFigures(false)
    }
  }, [])

  const generateVideo = useCallback(async (options) => {
    const { 
      figureId, 
      figureName,
      text, 
      voiceId, 
      width = 720,
      height = 1280,
      transparent = true,
      enableSubtitle = false,
      backgroundImageUrl
    } = options
    
    setIsGenerating(true)
    setGeneratedVideo(null)
    setError(null)
    
    try {
      const params = {
        figureId,
        driveType: 'TEXT',
        text,
        ...(backgroundImageUrl ? { backgroundImageUrl } : {}),
        ttsParams: {
          person: voiceId || '5116',
          speed: '5',
          pitch: '5',
          volume: '5'
        },
        videoParams: {
          width: parseInt(width),
          height: parseInt(height),
          transparent: !!transparent
        },
        subtitleParams: {
          enabled: !!enableSubtitle,
          subtitlePolicy: 'SRT'
        }
      }

      const response = await submitVideo(params)
      if (response.result && response.result.taskId) {
        startPolling(response.result.taskId, figureName)
        return response.result.taskId
      } else {
        throw new Error('TaskId missing')
      }
    } catch (err) {
      setIsGenerating(false)
      const msg = err.response?.data?.message?.global || '提交失败'
      setError(msg)
      message.error(msg)
      throw err
    }
  }, [startPolling])

  useEffect(() => {
    fetchFigures()
    return () => stopPolling()
  }, [fetchFigures, stopPolling])

  return {
    figures,
    femaleVoices,
    maleVoices,
    loadingFigures, 
    isGenerating, 
    generatedVideo, 
    error,
    generateVideo,
    resetGeneratedVideo: () => setGeneratedVideo(null)
  }
}
