/**
 * React Hook for Text Video Agent API
 */

import { useState, useCallback, useRef, useEffect } from 'react'
import { 
  textVideoAgentAPI, 
  ImageGenerationParams, 
  VideoGenerationParams,
  TaskRequest,
  APIResponse 
} from '../services/textVideoAgentAPI'

import {
  TaskType,
  AspectRatio,
  VideoDuration,
  TaskStatus as TaskStatusEnum
} from '../services/textVideoAgentTypes'

// Hook状态接口
interface UseTextVideoAgentState {
  isLoading: boolean
  error: string | null
  progress: number
  currentStep: string
  lastResult: any
}

// Hook返回值接口
interface UseTextVideoAgentReturn {
  // 状态
  state: UseTextVideoAgentState
  
  // 基础功能
  healthCheck: () => Promise<APIResponse>
  uploadFile: (file: File) => Promise<string | null>
  
  // 图片生成
  generateImage: (params: ImageGenerationParams) => Promise<string | null>
  generateImageAsync: (prompt: string, imgFile?: File) => Promise<string>
  
  // 视频生成
  generateVideo: (params: VideoGenerationParams) => Promise<string | null>
  generateVideoAsync: (params: VideoGenerationParams) => Promise<string>
  
  // 任务管理
  createTask: (request: TaskRequest) => Promise<string>
  getTaskStatus: (taskId: string) => Promise<any>
  
  // 高级功能
  generateContentEndToEnd: (
    prompt: string,
    options?: {
      taskType?: TaskType
      aspectRatio?: AspectRatio
      videoDuration?: VideoDuration
      generateVideo?: boolean
    }
  ) => Promise<{ imageUrl?: string; videoUrl?: string; taskId: string } | null>
  
  // 图片描述
  describeImage: (imageUrl: string) => Promise<string | null>
  describeImageByFile: (file: File) => Promise<string | null>
  
  // 工具函数
  reset: () => void
  cancel: () => void
}

/**
 * Text Video Agent API React Hook
 */
export function useTextVideoAgent(): UseTextVideoAgentReturn {
  const [state, setState] = useState<UseTextVideoAgentState>({
    isLoading: false,
    error: null,
    progress: 0,
    currentStep: '',
    lastResult: null
  })

  const abortControllerRef = useRef<AbortController | null>(null)

  // 更新状态的辅助函数
  const updateState = useCallback((updates: Partial<UseTextVideoAgentState>) => {
    setState(prev => ({ ...prev, ...updates }))
  }, [])

  // 重置状态
  const reset = useCallback(() => {
    setState({
      isLoading: false,
      error: null,
      progress: 0,
      currentStep: '',
      lastResult: null
    })
  }, [])

  // 取消当前操作
  const cancel = useCallback(() => {
    if (abortControllerRef.current) {
      abortControllerRef.current.abort()
      abortControllerRef.current = null
    }
    updateState({ isLoading: false, currentStep: '已取消' })
  }, [updateState])

  // 通用的异步操作包装器
  const withAsyncOperation = useCallback(async <T>(
    operation: () => Promise<T>,
    stepName: string
  ): Promise<T | null> => {
    try {
      updateState({ 
        isLoading: true, 
        error: null, 
        currentStep: stepName,
        progress: 0 
      })

      abortControllerRef.current = new AbortController()
      
      const result = await operation()
      
      updateState({ 
        isLoading: false, 
        progress: 100, 
        currentStep: '完成',
        lastResult: result 
      })
      
      return result
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '未知错误'
      updateState({ 
        isLoading: false, 
        error: errorMessage,
        currentStep: '错误'
      })
      console.error(`${stepName} 失败:`, error)
      return null
    } finally {
      abortControllerRef.current = null
    }
  }, [updateState])

  // 健康检查
  const healthCheck = useCallback(async (): Promise<APIResponse> => {
    return withAsyncOperation(
      () => textVideoAgentAPI.healthCheck(),
      '健康检查'
    ) as Promise<APIResponse>
  }, [withAsyncOperation])

  // 文件上传
  const uploadFile = useCallback(async (file: File): Promise<string | null> => {
    return withAsyncOperation(async () => {
      const result = await textVideoAgentAPI.uploadFile(file)
      return result.data || null
    }, '上传文件')
  }, [withAsyncOperation])

  // 图片生成（同步）
  const generateImage = useCallback(async (params: ImageGenerationParams): Promise<string | null> => {
    return withAsyncOperation(async () => {
      updateState({ progress: 20 })
      const result = await textVideoAgentAPI.generateImageWithRetry(params)
      return result.data?.image_url || result.data?.url || null
    }, '生成图片')
  }, [withAsyncOperation, updateState])

  // 图片生成（异步）
  const generateImageAsync = useCallback(async (prompt: string, imgFile?: File): Promise<string> => {
    const taskResult = await textVideoAgentAPI.generateImageAsync(prompt, imgFile)
    const taskId = taskResult.data?.task_id
    
    if (!taskId) {
      throw new Error('未获取到任务ID')
    }

    return taskId
  }, [])

  // 视频生成（同步）
  const generateVideo = useCallback(async (params: VideoGenerationParams): Promise<string | null> => {
    return withAsyncOperation(async () => {
      updateState({ progress: 20 })
      const result = await textVideoAgentAPI.generateVideoWithRetry(params)
      return result.data?.video_url || result.data?.url || null
    }, '生成视频')
  }, [withAsyncOperation, updateState])

  // 视频生成（异步）
  const generateVideoAsync = useCallback(async (params: VideoGenerationParams): Promise<string> => {
    const taskResult = await textVideoAgentAPI.generateVideoAsync(params)
    const taskId = taskResult.data?.task_id
    
    if (!taskId) {
      throw new Error('未获取到任务ID')
    }

    return taskId
  }, [])

  // 创建任务
  const createTask = useCallback(async (request: TaskRequest): Promise<string> => {
    const result = await textVideoAgentAPI.createTask(request)
    const taskId = result.data?.task_id
    
    if (!taskId) {
      throw new Error('任务创建失败')
    }

    return taskId
  }, [])

  // 获取任务状态
  const getTaskStatus = useCallback(async (taskId: string): Promise<any> => {
    const result = await textVideoAgentAPI.getTaskStatusAsync(taskId)
    return result.data
  }, [])

  // 端到端内容生成
  const generateContentEndToEnd = useCallback(async (
    prompt: string,
    options: {
      taskType?: TaskType
      aspectRatio?: AspectRatio
      videoDuration?: VideoDuration
      generateVideo?: boolean
    } = {}
  ): Promise<{ imageUrl?: string; videoUrl?: string; taskId: string } | null> => {
    return withAsyncOperation(async () => {
      const result = await textVideoAgentAPI.generateContentEndToEnd(prompt, {
        ...options,
        onProgress: (step, progress) => {
          updateState({ currentStep: step, progress })
        }
      })
      return result
    }, '端到端内容生成')
  }, [withAsyncOperation, updateState])

  // 图片描述（通过URL）
  const describeImage = useCallback(async (imageUrl: string): Promise<string | null> => {
    return withAsyncOperation(async () => {
      const result = await textVideoAgentAPI.describeImageByUrl({ image_url: imageUrl })
      return result.data?.description || null
    }, '分析图片')
  }, [withAsyncOperation])

  // 图片描述（通过文件）
  const describeImageByFile = useCallback(async (file: File): Promise<string | null> => {
    return withAsyncOperation(async () => {
      const result = await textVideoAgentAPI.describeImageByFile({ img_file: file })
      return result.data?.description || null
    }, '分析图片')
  }, [withAsyncOperation])

  // 清理资源
  useEffect(() => {
    return () => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort()
      }
    }
  }, [])

  return {
    state,
    healthCheck,
    uploadFile,
    generateImage,
    generateImageAsync,
    generateVideo,
    generateVideoAsync,
    createTask,
    getTaskStatus,
    generateContentEndToEnd,
    describeImage,
    describeImageByFile,
    reset,
    cancel
  }
}

/**
 * 任务轮询Hook
 */
export function useTaskPolling(
  taskId: string | null,
  options: {
    enabled?: boolean
    interval?: number
    maxDuration?: number
    onComplete?: (result: any) => void
    onError?: (error: string) => void
    onProgress?: (status: any) => void
  } = {}
) {
  const {
    enabled = true,
    interval = 2000,
    maxDuration = 300000, // 5分钟
    onComplete,
    onError,
    onProgress
  } = options

  const [status, setStatus] = useState<any>(null)
  const [isPolling, setIsPolling] = useState(false)
  const intervalRef = useRef<NodeJS.Timeout | null>(null)
  const startTimeRef = useRef<number>(0)

  const startPolling = useCallback(async () => {
    if (!taskId || !enabled) return

    setIsPolling(true)
    startTimeRef.current = Date.now()

    const poll = async () => {
      try {
        const result = await textVideoAgentAPI.getTaskStatusAsync(taskId)
        const taskStatus = result.data

        setStatus(taskStatus)
        onProgress?.(taskStatus)

        // 检查是否完成
        if (taskStatus?.status === TaskStatusEnum.COMPLETED) {
          setIsPolling(false)
          onComplete?.(taskStatus)
          if (intervalRef.current) {
            clearInterval(intervalRef.current)
            intervalRef.current = null
          }
          return
        }

        // 检查是否失败
        if (taskStatus?.status === TaskStatusEnum.FAILED) {
          setIsPolling(false)
          onError?.(taskStatus?.error || '任务失败')
          if (intervalRef.current) {
            clearInterval(intervalRef.current)
            intervalRef.current = null
          }
          return
        }

        // 检查是否超时
        if (Date.now() - startTimeRef.current > maxDuration) {
          setIsPolling(false)
          onError?.('任务超时')
          if (intervalRef.current) {
            clearInterval(intervalRef.current)
            intervalRef.current = null
          }
          return
        }
      } catch (error) {
        console.error('轮询任务状态失败:', error)
        onError?.(error instanceof Error ? error.message : '轮询失败')
      }
    }

    // 立即执行一次
    await poll()

    // 设置定时轮询
    if (isPolling) {
      intervalRef.current = setInterval(poll, interval)
    }
  }, [taskId, enabled, interval, maxDuration, onComplete, onError, onProgress])

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

  // 自动开始轮询
  useEffect(() => {
    if (taskId && enabled) {
      startPolling()
    }

    return () => {
      stopPolling()
    }
  }, [taskId, enabled, startPolling, stopPolling])

  return {
    status,
    isPolling,
    startPolling,
    stopPolling
  }
}
