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 components
import MarketSettings from './components/MarketSettings.vue'
import MerchantStore from './components/MerchantStore.vue'
import ShoppingCart from './components/ShoppingCart.vue'

// NostrmarketService will be dynamically imported in install()

// Store will be imported when needed

// Import composables
import { useMarket } from './composables/useMarket'
import { useMarketPreloader } from './composables/useMarketPreloader'

// Import services
import { NostrmarketService } from './services/nostrmarketService'
import { PaymentMonitorService } from './services/paymentMonitor'
import { NostrmarketAPI } from './services/nostrmarketAPI'

export interface MarketModuleConfig {
  defaultCurrency: string
  paymentTimeout: number
  maxOrderHistory: number
  supportedRelays?: string[]
}

/**
 * Market Module Plugin
 * Provides market, stall, and product management functionality
 */
export const marketModule: ModulePlugin = {
  name: 'market',
  version: '1.0.0',
  dependencies: ['base'],

  async install(app: App, options?: { config?: MarketModuleConfig }) {
    console.log('🛒 Installing market module...')

    const config = options?.config
    if (!config) {
      throw new Error('Market module requires configuration')
    }

    // Create and register service instances
    const nostrmarketService = new NostrmarketService()
    container.provide(SERVICE_TOKENS.NOSTRMARKET_SERVICE, nostrmarketService)
    
    const nostrmarketAPI = new NostrmarketAPI()
    container.provide(SERVICE_TOKENS.NOSTRMARKET_API, nostrmarketAPI)
    
    const paymentMonitorService = new PaymentMonitorService()
    container.provide(SERVICE_TOKENS.PAYMENT_MONITOR, paymentMonitorService)
    
    // Initialize services (will handle dependency injection)
    await nostrmarketService.initialize({
      waitForDependencies: true,
      maxRetries: 3
    }).catch(error => {
      console.warn('🛒 NostrmarketService initialization deferred:', error)
      // Service will auto-initialize when dependencies are available
    })
    
    await nostrmarketAPI.initialize({
      waitForDependencies: true,
      maxRetries: 3
    }).catch(error => {
      console.warn('🛒 NostrmarketAPI initialization deferred:', error)
      // Service will auto-initialize when dependencies are available
    })
    
    await paymentMonitorService.initialize({
      waitForDependencies: true,
      maxRetries: 3
    }).catch(error => {
      console.warn('🛒 PaymentMonitorService initialization deferred:', error)
      // Service will auto-initialize when dependencies are available
    })

    // Register global components
    app.component('MarketSettings', MarketSettings)
    app.component('MerchantStore', MerchantStore)
    app.component('ShoppingCart', ShoppingCart)

    // Market store will be initialized when first used
    
    // Set up event listeners for integration with other modules
    setupEventListeners()

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

  async uninstall() {
    console.log('🗑️ Uninstalling market module...')
    
    // Clean up services
    container.remove(SERVICE_TOKENS.NOSTRMARKET_SERVICE)
    container.remove(SERVICE_TOKENS.NOSTRMARKET_API)
    container.remove(SERVICE_TOKENS.PAYMENT_MONITOR)
    
    console.log('✅ Market module uninstalled')
  },

  routes: [
    {
      path: '/market',
      name: 'market',
      component: () => import('./views/MarketPage.vue'),
      meta: {
        title: 'Market',
        requiresAuth: false
      }
    },
    {
      path: '/market/dashboard',
      name: 'market-dashboard',
      component: () => import('./views/MarketDashboard.vue'),
      meta: {
        title: 'Market Dashboard',
        requiresAuth: true
      }
    },
    {
      path: '/market-dashboard',
      redirect: '/market/dashboard'
    },
    {
      path: '/cart',
      name: 'cart',
      component: () => import('./views/CartPage.vue'),
      meta: {
        title: 'Shopping Cart',
        requiresAuth: false
      }
    },
    {
      path: '/checkout/:stallId',
      name: 'checkout',
      component: () => import('./views/CheckoutPage.vue'),
      meta: {
        title: 'Checkout',
        requiresAuth: false
      }
    }
  ] as RouteRecordRaw[],

  components: {
    MarketSettings,
    MerchantStore,
    ShoppingCart
  },

  composables: {
    useMarket,
    useMarketPreloader
  },

  services: {
    nostrmarket: SERVICE_TOKENS.NOSTRMARKET_SERVICE
  }
}

// Set up event listeners for integration with other modules
function setupEventListeners() {
  // Listen for auth events
  eventBus.on('auth:logout', () => {
    console.log('Market module: user logged out, clearing market data')
    // Could clear market-specific user data here
  })

  // Listen for payment events from other modules
  eventBus.on('payment:completed', (event) => {
    console.log('Market module: payment completed', event.data)
    // Could update order status or refresh market data here
  })

  // Emit market-specific events
  eventBus.on('market:order-placed', (event) => {
    console.log('Market order placed:', event.data)
    // Other modules can listen to this event
  })

  eventBus.on('market:product-added', (event) => {
    console.log('Market product added:', event.data)
    // Other modules can listen to this event
  })
}

export default marketModule

// Re-export types and composables for external use
export type * from './types/market'
export { useMarket, useMarketPreloader } from './composables'
export { useMarketStore } from './stores/market'
