import md5 from 'js-md5'
import { fetchEventSource } from '@fortaine/fetch-event-source'
import { useState, useCallback } from 'react'

export function useAIChat() {
  const authKey = 'f3846153ba784b6d86bdcd5533259c88'
  const authSecret = 'HO4IyLEwEOHpeOXBxaLQUOqWslJRGs1M'

  const [messages, setMessages] = useState([])
  const [chatId, setChatId] = useState(null)
  const [isLoading, setIsLoading] = useState(false)

  const addMessage = useCallback((message) => {
    setMessages((prevMessages) => [...prevMessages, message])
  }, [])

  const updateMessages = useCallback((newMessage) => {
    setMessages((prevMessages) => {
      const existingMessage = prevMessages.find((msg) => msg.conversationId === newMessage.conversationId)

      const content = newMessage.content === '\n' ? '<br/>' : newMessage.content || ''

      if (existingMessage) {
        // 更新现有消息
        return prevMessages.map((msg) =>
          msg.conversationId === newMessage.conversationId ? { ...msg, content: msg.content + content } : msg
        )
      } else {
        // 新增消息
        return [...prevMessages, { ...newMessage, content, role_type: 'ai', time: Date.now() }]
      }
    })
  }, [])

  const post = useCallback(
    async (data) => {
      const timestamp = Date.now()
      const sign = md5(`${authKey}${authSecret}${timestamp}`)

      // 插入用户消息
      addMessage({
        role_type: 'user',
        content: data.content,
        conversationId: `user-${timestamp}`, // 生成一个唯一的 conversationId
        time: Date.now(),
      })

      setIsLoading(true)

      try {
        await fetchEventSource('/api/tiangong/openapi/agent/chat/stream/v1', {
          method: 'POST',
          headers: {
            authKey,
            timestamp,
            sign,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ ...data, chatId, agentId: authKey }),
          onopen(response) {
            if (!response.ok) {
              throw new Error('Network response was not ok')
            }
          },
          onmessage(event) {
            const message = JSON.parse(event.data)
            setChatId(message.chatId)
            updateMessages(message)
          },
          onerror(error) {
            console.error('Fetch error:', error)
          },
          onclose() {
            setIsLoading(false)
          },
        })
      } catch (error) {
        console.error('Post error:', error)
        setIsLoading(false)
      }
    },
    [authKey, authSecret, chatId, addMessage, updateMessages]
  )

  return { messages, isLoading, post }
}
