import { computed } from 'vue'
import { useMarketStore } from '../stores/market'
import { injectService, SERVICE_TOKENS } from '@/core/di-container'
import type { PaymentService } from '@/core/services/PaymentService'

export function useLightningPayment() {
  const paymentService = injectService(SERVICE_TOKENS.PAYMENT_SERVICE) as PaymentService
  const marketStore = useMarketStore()

  // Computed properties - delegate to PaymentService
  const userWallets = computed(() => paymentService.userWallets) // getter method
  const hasWalletWithBalance = computed(() => paymentService.hasWalletWithBalance) // getter method  
  const isPayingWithWallet = computed(() => paymentService.isProcessingPayment.value) // computed ref
  const paymentError = computed(() => paymentService.paymentError.value) // computed ref

  // Get wallet with sufficient balance - delegate to PaymentService
  const getWalletWithBalance = (requiredAmountSats?: number) => {
    return paymentService.getWalletWithBalance(requiredAmountSats)
  }

  // Pay Lightning invoice with user's wallet
  async function payInvoice(paymentRequest: string, orderId?: string): Promise<boolean> {
    try {
      // Use PaymentService with custom success message
      const paymentResult = await paymentService.payWithWallet(
        paymentRequest,
        undefined, // No specific amount requirement
        {
          successMessage: orderId 
            ? `Order ${orderId.slice(-8)} has been paid` 
            : 'Lightning invoice paid successfully'
        }
      )

      // Update order status to paid if orderId is provided
      if (orderId) {
        const order = marketStore.orders[orderId]
        if (order) {
          const updatedOrder = {
            ...order,
            paymentStatus: 'paid' as const,
            status: 'paid' as const,
            paidAt: Math.floor(Date.now() / 1000),
            paymentHash: paymentResult.payment_hash,
            feeMsat: paymentResult.fee_msat,
            items: [...order.items], // Convert readonly to mutable
            shippingZone: order.shippingZone ? {
              ...order.shippingZone,
              countries: order.shippingZone.countries ? [...order.shippingZone.countries] : undefined
            } : order.shippingZone
          }
          marketStore.updateOrder(orderId, updatedOrder)
        }
      }

      return true
    } catch (error) {
      throw error // PaymentService already handled error notifications
    }
  }

  // Open external Lightning wallet (fallback) - delegate to PaymentService
  function openExternalLightningWallet(paymentRequest: string) {
    paymentService.openExternalWallet(paymentRequest)
  }

  // Main payment handler - tries wallet first, falls back to external
  async function handlePayment(paymentRequest: string, orderId?: string): Promise<void> {
    try {
      // Use PaymentService's automatic fallback handling
      const result = await paymentService.handlePayment(
        paymentRequest,
        undefined, // No specific amount requirement
        {
          successMessage: orderId 
            ? `Order ${orderId.slice(-8)} has been paid` 
            : 'Lightning invoice paid successfully'
        }
      )

      // If payment was successful with wallet, update order
      if (result && orderId) {
        const order = marketStore.orders[orderId]
        if (order) {
          const updatedOrder = {
            ...order,
            paymentStatus: 'paid' as const,
            status: 'paid' as const,
            paidAt: Math.floor(Date.now() / 1000),
            paymentHash: result.payment_hash,
            feeMsat: result.fee_msat,
            items: [...order.items], // Convert readonly to mutable
            shippingZone: order.shippingZone ? {
              ...order.shippingZone,
              countries: order.shippingZone.countries ? [...order.shippingZone.countries] : undefined
            } : order.shippingZone
          }
          marketStore.updateOrder(orderId, updatedOrder)
        }
      }
      // If result is null, external wallet was opened (fallback case)
    } catch (error) {
      // PaymentService already handled error notifications
      throw error
    }
  }

  return {
    // State
    isPayingWithWallet,
    paymentError,
    
    // Computed
    hasWalletWithBalance,
    userWallets,
    
    // Methods
    payInvoice,
    openExternalLightningWallet,
    handlePayment,
    getWalletWithBalance
  }
}