import { useState, useCallback } from 'react'
import type { SendMessagePayload } from '../types'
import type { PlatformConfig } from './useNovaEvents'

interface UseMessageSenderProps {
  conversationId?: string
  platformConfig?: PlatformConfig
  sendMessage?: (message: string) => void
  agentId?: string
}

export function useMessageSender({
  conversationId,
  platformConfig,
  sendMessage,
  agentId,
}: UseMessageSenderProps) {
  const [sendingMessage, setSendingMessage] = useState(false)

  // Send Message Logic
  const handleSend = useCallback(
    (payload: SendMessagePayload) => {
      // If platformConfig is provided, send via WebSocket
      if (platformConfig && sendMessage) {
        try {
          setSendingMessage(true)
          const message = {
            message_type: 'chat',
            conversation_id: conversationId,
            agent_id: agentId,
            agent_model: 'Nova Pro',
            content: payload.content,
            refer_content: payload.refer_content || '',
            upload_file_ids: payload.upload_file_ids,
          }
          sendMessage(JSON.stringify(message))
        } catch (error) {
          console.error('Failed to send message via WebSocket:', error)
          setSendingMessage(false)
        }
      }
    },
    [platformConfig, sendMessage, conversationId, agentId]
  )

  return {
    sendingMessage,
    setSendingMessage,
    handleSend
  }
}
