import { useState, useEffect, useCallback, useRef } from 'react'
import { AI_OPTIONS } from './config'
import aiService from './api'
import type { AIMessage, AIRequestData, GenerateImageRequestData, GenerateVideoRequestData } from './types'
import { RequestOptions } from './request'

export function useAI(globalOptions?: RequestOptions) {
  const [ai, setAI] = useState<string>(localStorage.getItem('ai') || 'Pro/deepseek-ai/DeepSeek-R1')
  const [messages, setMessages] = useState<AIMessage[]>([])
  const [message, setMessage] = useState<AIMessage | null>(null)
  const [isLoading, setIsLoading] = useState<boolean>(false)
  const [error, setError] = useState<string | null>(null)
  const controllerRef = useRef<AbortController | null>(null)
  useEffect(() => {
    localStorage.setItem('ai', ai)
  }, [ai])

  const clearError = useCallback(() => {
    setError(null)
  }, [])

  const abort = useCallback(() => {
    if (controllerRef.current) {
      controllerRef.current.abort()
      controllerRef.current = null
      setIsLoading(false)
    }
  }, [])

  const callback = (message: AIMessage) => {
    setMessage(message)
    setMessages((prev) => {
      const messageIndex = prev.findIndex((item) => item.id === message.id)
      return messageIndex === -1 ? [...prev, message] : prev.map((item) => (item.id === message.id ? message : item))
    })
  }

  const post = useCallback(
    async (data: AIRequestData, method?: string) => {
      // 如果已经有正在进行的请求，先取消它
      abort()

      return new Promise<AIMessage>((resolve, reject) => {
        setIsLoading(true)
        setError(null)

        // 创建新的 controller
        controllerRef.current = new AbortController()
        // 添加用户消息
        if ('messages' in data) {
          const userMessages = data.messages.filter((item) => item.role !== 'system')
          setMessages((prev) => [...prev, ...userMessages])
        }

        aiService.post(
          { model: ai, ...data },
          {
            signal: controllerRef.current.signal,
            onUpdate: (message) => {
              callback(message)
            },
            onSuccess: (message) => {
              callback(message)
              controllerRef.current = null
              setIsLoading(false)
              resolve(message)
            },
            onError: (err) => {
              controllerRef.current = null
              setIsLoading(false)
              setError(err.message)
              reject(err)
            },
            ...globalOptions,
          },
          method
        )
      })
    },
    [ai, globalOptions, abort]
  )

  const clear = useCallback(() => {
    setMessages([])
  }, [])

  // 文生图
  const generateImage = useCallback(async (data: GenerateImageRequestData) => post(data, 'imageCreate'), [post])

  // 文生视频
  const generateVideo = useCallback(async (data: GenerateVideoRequestData) => post(data, 'videoCreate'), [post])

  // 组件卸载时取消请求
  useEffect(() => {
    return () => {
      abort()
    }
  }, [abort])

  return {
    ai,
    setAI,
    options: AI_OPTIONS,
    post,
    messages,
    message,
    isLoading,
    error,
    clearError,
    abort,
    clear,
    generateImage,
    generateVideo,
  }
}
