import { useState, useCallback } from 'react'
import { baiduAIChat } from '@/api/ai'

export function useAIEdit() {
  const [messages, setMessages] = useState([])
  const [isLoading, setIsLoading] = useState(false)
  const latestMessage = messages[messages.length - 1] || {}
  const text = latestMessage?.content || ''

  const fetch = useCallback(async (params) => {
    setIsLoading(true)
    try {
      const defaultParams = { ernie_name: 'ERNIE-4.0-8K-Preview', stream: false }
      const res = await baiduAIChat({ ...defaultParams, params })
      const message = { role: 'assistant', content: res.data.result }
      setMessages((prevMessages) => [...prevMessages, message])
    } catch (error) {
      console.error('Error fetching data:', error)
    } finally {
      setIsLoading(false)
    }
  }, [])

  return { text, messages, isLoading, fetch }
}
