import { useState, useEffect, useCallback } from 'react'
import axios from 'axios'

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

  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
          default:
            throw new Error('未找到对应的 AI 配置')
        }
      } catch (err) {
        console.error('AI 请求失败:', err)
      } finally {
        setIsLoading(false)
      }
    },
    [ai],
  )

  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 }])
    }
  }

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

export function useGenerateImage() {}

export function useGenerateVideo() {}
