import { useState } from 'react'
import { aiEdit, aiChat, aiGenerateImage } from '@/api/ai'

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

  const fetch = async params => {
    setIsLoading(true)
    try {
      const res = await aiEdit({
        body: JSON.stringify({ params }),
        onmessage: res => {
          let message = JSON.parse(res.data)
          message = { ...message.data, request_id: message.request_id }
          setMessages(prevMessages => {
            const messageIndex = prevMessages.findIndex(m => m.request_id === message.request_id)
            if (messageIndex === -1) {
              return [...prevMessages, message]
            } else {
              return prevMessages.map(m => (m.request_id === message.request_id ? message : m))
            }
          })
        }
      })
    } catch (error) {
      console.error('Error fetching AI edit:', error)
    } finally {
      setIsLoading(false)
    }
  }

  return { messages, text, setMessages, fetch, isLoading }
}

export function useAIChat() {
  const [messages, setMessages] = useState([])
  const fetch = async params => {
    const res = await aiChat({
      body: JSON.stringify({ params }),
      onmessage: res => {
        const message = JSON.parse(res.data)
        console.log(message)
        setMessages(messages => [...messages, message])
      }
    })
  }
}

export function useAIGenerateImage() {
  const [messages, setMessages] = useState([])
  const fetch = async params => {
    const res = await aiGenerateImage(params)
    setMessages(res)
  }
}
