import { ref, computed } from 'vue'
import { injectService, SERVICE_TOKENS } from '@/core/di-container'
import type { ChatService } from '../services/chat-service'
import type { ChatPeer } from '../types'
import { useMultiAsyncOperation } from '@/core/composables/useAsyncOperation'

// Use standardized service token from DI container
export const CHAT_SERVICE_TOKEN = SERVICE_TOKENS.CHAT_SERVICE

export function useChat() {
  const chatService = injectService<ChatService>(CHAT_SERVICE_TOKEN)
  
  if (!chatService) {
    throw new Error('ChatService not available. Make sure chat module is installed.')
  }

  const selectedPeer = ref<string | null>(null)
  
  // Async operations
  const asyncOps = useMultiAsyncOperation<{
    sendMessage: void
    refreshPeers: void
  }>()
  
  const sendMessageOp = asyncOps.createOperation('sendMessage')
  const refreshPeersOp = asyncOps.createOperation('refreshPeers')

  // Computed properties
  const peers = computed(() => chatService.allPeers.value)
  const totalUnreadCount = computed(() => chatService.totalUnreadCount.value)
  const isReady = computed(() => chatService.isReady.value)
  
  const currentMessages = computed(() => {
    return selectedPeer.value ? chatService.getMessages(selectedPeer.value) : []
  })

  const currentPeer = computed(() => {
    return selectedPeer.value ? chatService.getPeer(selectedPeer.value) : undefined
  })

  // Methods
  const selectPeer = (peerPubkey: string) => {
    selectedPeer.value = peerPubkey
    chatService.markAsRead(peerPubkey)
  }

  const sendMessage = async (content: string) => {
    if (!selectedPeer.value || !content.trim()) {
      return
    }

    return await sendMessageOp.execute(async () => {
      await chatService.sendMessage(selectedPeer.value!, content.trim())
    }, {
      errorMessage: 'Failed to send message'
    })
  }

  const addPeer = (pubkey: string, name?: string): ChatPeer => {
    return chatService.addPeer(pubkey, name)
  }

  const markAsRead = (peerPubkey: string) => {
    chatService.markAsRead(peerPubkey)
  }

  const refreshPeers = async () => {
    return await refreshPeersOp.execute(async () => {
      await chatService.refreshPeers()
    }, {
      errorMessage: 'Failed to refresh peers'
    })
  }

  return {
    // State
    selectedPeer,
    isSendingMessage: sendMessageOp.isLoading,
    sendMessageError: sendMessageOp.error,
    isRefreshingPeers: refreshPeersOp.isLoading,
    refreshPeersError: refreshPeersOp.error,
    isLoading: computed(() => asyncOps.isAnyLoading()),
    error: computed(() => sendMessageOp.error.value || refreshPeersOp.error.value),
    
    // Computed
    peers,
    totalUnreadCount,
    isReady,
    currentMessages,
    currentPeer,
    
    // Methods
    selectPeer,
    sendMessage,
    addPeer,
    markAsRead,
    refreshPeers
  }
}