import type { App } from 'vue'
import type { ModulePlugin } from '@/core/types'
import type { RouteRecordRaw } from 'vue-router'
import { container, SERVICE_TOKENS } from '@/core/di-container'
import { eventBus } from '@/core/event-bus'

// Import chat components and services
import ChatComponent from './components/ChatComponent.vue'
import { ChatService } from './services/chat-service'
import { useChat } from './composables/useChat'
import type { ChatConfig } from './types'

/**
 * Chat Module Plugin
 * Provides Nostr-based encrypted chat functionality
 */
export const chatModule: ModulePlugin = {
  name: 'chat',
  version: '1.0.0',
  dependencies: ['base'],

  async install(app: App, options?: { config?: ChatConfig }) {
    console.log('💬 Installing chat module...')

    const config: ChatConfig = {
      maxMessages: 500,
      autoScroll: true,
      showTimestamps: true,
      notificationsEnabled: true,
      soundEnabled: false,
      ...options?.config
    }

    // Create and register chat service
    const chatService = new ChatService(config)
    container.provide(SERVICE_TOKENS.CHAT_SERVICE, chatService)
    
    // Initialize the service (will handle dependency injection)
    await chatService.initialize({
      waitForDependencies: true,
      maxRetries: 3
    }).catch(error => {
      console.warn('💬 Chat service initialization deferred:', error)
      // Service will auto-initialize when dependencies are available
    })
    
    // Also make it globally available for other modules (like market)
    ;(globalThis as any).chatService = chatService

    // Register global components
    app.component('ChatComponent', ChatComponent)

    // Set up event listeners for integration with other modules
    setupEventListeners(chatService)

    console.log('✅ Chat module installed successfully')
  },

  async uninstall() {
    console.log('🗑️ Uninstalling chat module...')
    
    // Clean up chat service
    const chatService = container.inject<ChatService>(SERVICE_TOKENS.CHAT_SERVICE)
    if (chatService) {
      chatService.destroy()
      container.remove(SERVICE_TOKENS.CHAT_SERVICE)
    }
    
    console.log('✅ Chat module uninstalled')
  },

  routes: [
    {
      path: '/chat',
      name: 'chat',
      component: () => import('./views/ChatPage.vue'),
      meta: {
        title: 'Nostr Chat',
        requiresAuth: true
      }
    }
  ] as RouteRecordRaw[],

  components: {
    ChatComponent
  },

  composables: {
    useChat
  },

  services: {
    chatService: SERVICE_TOKENS.CHAT_SERVICE
  }
}

// Private function to set up event listeners
function setupEventListeners(chatService: ChatService) {
  // Listen for auth events to clear chat data on logout
  eventBus.on('auth:logout', () => {
    chatService.destroy()
  })

  // Listen for Nostr events that might be chat messages
  eventBus.on('nostr:event', (event) => {
    // TODO: Process incoming Nostr events for encrypted DMs
    console.log('Received Nostr event in chat module:', event)
  })

  // Emit chat events for other modules to listen to
  // This is already handled by the ChatService via eventBus
}

export default chatModule

// Re-export types and composables for external use
export type { ChatMessage, ChatPeer, ChatConfig } from './types'
export { useChat } from './composables/useChat'