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

export function useAI() {
  const options = [
    { label: '文心一言', value: 'yiyan' },
    { label: 'DeepSeek', value: 'deepseek' },
    { label: '通义千问', value: 'qwen' },
    { label: '天工', value: 'tiangong' },
  ]

  const [ai, setAI] = useState(localStorage.getItem('ai') || 'yiyan')
  const [messages, setMessages] = useState([])
  const [isLoading, setIsLoading] = useState(false)

  useEffect(() => {
    localStorage.setItem('ai', ai)
  }, [ai])

  const post = useCallback(
    async (data) => {
      setIsLoading(true)
      setMessages((prevMessages) => [...prevMessages, { role: 'user', content: data.content }])
      try {
        switch (ai) {
          case 'yiyan':
            await yiyan(data)
            break
          case 'deepseek':
            await deepseek(data)
            break
          case 'qwen':
            await qwen(data)
            break
          case 'tiangong':
            await tiangong(data)
            break
          default:
            throw new Error('未找到对应的 AI 配置')
        }
      } catch (err) {
        console.error('AI 请求失败:', err)
      } finally {
        setIsLoading(false)
      }
    },
    [ai] // 依赖 `ai`，当 `ai` 变化时，重新创建 `post`
  )

  async function yiyan(data) {
    const getAccessToken = async () => {
      const AK = 'wY7bvMpkWeZbDVq9w3EDvpjU'
      const SK = 'XJwpiJWxs5HXkOtbo6tQrvYPZFJAWdAy'
      const resp = await axios.post(
        `/api/qianfan/oauth/2.0/token?grant_type=client_credentials&client_id=${AK}&client_secret=${SK}`
      )
      return resp.data.access_token
    }
    const resp = await axios.post(
      `/api/qianfan/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token=${await getAccessToken()}`,
      {
        messages: [{ role: 'user', content: data.content }],
      }
    )
    setMessages((prevMessages) => [...prevMessages, { role: 'assistant', content: resp.data.result }])
  }

  async function deepseek(data) {
    const apiKey = 'sk-f1a6f0a7013241de8393cb2cb108e777'
    const resp = await axios.post(
      '/api/deepseek/chat/completions',
      {
        model: 'deepseek-chat',
        messages: [{ role: 'user', content: data.content }],
      },
      {
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}` },
      }
    )
    if (resp.data) {
      const [choice = {}] = resp.data.choices
      setMessages((prevMessages) => [...prevMessages, { role: 'assistant', content: choice.message.content }])
    }
  }

  async function qwen(data) {
    const apiKey = 'sk-afd0fcdb53bf4058b2068b8548820150'
    const resp = await axios.post(
      '/api/qwen/compatible-mode/v1/chat/completions',
      {
        model: 'qwen-max',
        messages: [{ role: 'user', content: data.content }],
      },
      {
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}` },
      }
    )
    if (resp.data) {
      const [choice = {}] = resp.data.choices
      setMessages((prevMessages) => [...prevMessages, { role: 'assistant', content: choice.message.content }])
    }
  }

  async function tiangong(data) {
    const appKey = 'a8701b73637562d33a53c668a90ee3be'
    const appSecret = 'e191593f486bb88a39c634f46926762dddc97b9082e192af'
    const timestamp = Math.floor(Date.now() / 1000)
    const sign = md5(`${appKey}${appSecret}${timestamp}`)

    return await fetchEventSource('/api/tiangong/sky-saas-writing/api/v1/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', app_key: appKey, sign, timestamp, stream: 'true' },
      body: JSON.stringify({
        chat_history: [{ role: 'user', content: data.content }],
        stream_resp_type: 'update',
      }),
      async onopen(response) {
        console.log(response)
        if (response.ok) {
          return response
        } else {
          throw response
        }
      },
      onmessage(res) {
        console.log(res.data)
        const message = JSON.parse(res.data)
        if (message.type !== 1) return
        setMessages((prevMessages) => {
          const messageId = message.conversation_id
          const messageIndex = prevMessages.findIndex((message) => message.id === messageId)
          const content = message?.arguments?.[0]?.messages?.[0]?.text || ''
          if (messageIndex === -1) {
            return [...prevMessages, { id: messageId, role: 'assistant', content }]
          } else {
            return prevMessages.map((msg) => (msg.id === messageId ? { ...msg, content } : msg))
          }
        })
        setIsLoading(false)
      },
      onerror(err) {
        setIsLoading(false)
        throw err
      },
    })
  }

  return { ai, setAI, options, post, messages, isLoading }
}
