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)

  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')
        setMessages((prev) => [...prev, ...userMessages])

        aiService.post(
          { model: ai, ...data },
          {
            signal: controllerRef.current.signal,
            onUpdate: (message) => {
              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))
              })
            },
            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,
  }
}
