import { useState, useEffect, useCallback, useRef } from 'react'
import { AI_OPTIONS } from './config'
import aiService from './api'
import type { AIMessage, AIData } from './types'
import { SSEOptions } from '@/utils/sseRequest'

export function useAI(globalOptions?: SSEOptions) {
  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)

  // 使用 useRef 存储最新消息，避免闭包问题
  const latestMessageRef = useRef<AIMessage | null>(null)
  // 使用 useRef 存储消息列表，避免异步更新问题
  const messagesRef = useRef<AIMessage[]>([])

  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 post = useCallback(
    async (data: AIData) => {
      // 如果已经有正在进行的请求，先取消它
      abort()

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

        // 创建新的 controller
        controllerRef.current = new AbortController()

        // 添加用户消息
        const userMessages = data.messages.filter((item) => item.role !== 'system')
        messagesRef.current = [...messagesRef.current, ...userMessages]
        setMessages((prev) => [...prev, ...userMessages])

        aiService.post(
          { model: ai, ...data },
          {
            signal: controllerRef.current.signal,
            onUpdate: (message) => {
              const messageIndex = messagesRef.current.findIndex((msg) => msg.id === message.id)

              if (messageIndex === -1) {
                // 新消息
                latestMessageRef.current = message
                messagesRef.current = [...messagesRef.current, message]
                setMessage(message)
                setMessages(messagesRef.current)
              } else {
                // 更新现有消息
                messagesRef.current = messagesRef.current.map((msg) => {
                  if (msg.id === message.id) {
                    const updatedMessage = {
                      ...msg,
                      content: msg.content + message.content,
                      reasoning_content: msg.reasoning_content + message.reasoning_content,
                    }
                    latestMessageRef.current = updatedMessage
                    setMessage(updatedMessage)
                    return updatedMessage
                  }
                  return msg
                })
                setMessages([...messagesRef.current])
              }
            },
            onSuccess: (message) => {
              controllerRef.current = null
              setIsLoading(false)
              resolve(message)
            },
            onError: (err) => {
              controllerRef.current = null
              setIsLoading(false)
              setError(err.message)
              reject(err)
            },
            ...globalOptions,
          }
        )
      })
    },
    [ai, globalOptions, abort]
  )

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

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