import { ref } from 'vue'
import { useAuth } from '@/composables/useAuthService'
import { useMarketStore } from '../stores/market'

// Simplified bolt11 parser to extract payment hash
function parseBolt11(_bolt11: string): { paymentHash?: string } {
  try {
    // Very basic bolt11 parsing - in a real app you'd use a proper library
    // For now, we'll return empty since this requires complex bech32 decoding
    // Note: Remove lightning: prefix if present: bolt11.replace(/^lightning:/, '')
    return {}
  } catch (error) {
    console.error('Failed to parse bolt11:', error)
    return {}
  }
}

export function usePaymentStatusChecker() {
  const { currentUser } = useAuth()
  const marketStore = useMarketStore()
  const isChecking = ref(false)

  // Check payment status via LNbits API using payment hash
  async function checkPaymentStatusByHash(paymentHash: string, walletId?: string): Promise<boolean> {
    if (!currentUser.value || !paymentHash) {
      return false
    }

    try {
      // Get wallet with admin key
      const wallet = walletId 
        ? currentUser.value.wallets?.find((w: any) => w.id === walletId)
        : currentUser.value.wallets?.find((w: any) => w.adminkey) // Use first wallet with admin key

      if (!wallet || !wallet.adminkey) {
        console.warn('No wallet with admin key found for payment status check')
        return false
      }

      // Check payment status via LNbits API
      const response = await fetch(`/api/v1/payments/${paymentHash}`, {
        headers: {
          'accept': 'application/json',
          'X-API-KEY': wallet.adminkey,
        },
      })

      if (response.ok) {
        const payment = await response.json()
        return payment.paid === true
      } else {
        console.warn('Payment not found or API error:', response.status)
        return false
      }
    } catch (error) {
      console.error('Failed to check payment status:', error)
      return false
    }
  }

  // Check payment status for a bolt11 invoice
  async function checkPaymentStatusByBolt11(bolt11: string): Promise<boolean> {
    const parsed = parseBolt11(bolt11)
    if (parsed.paymentHash) {
      return await checkPaymentStatusByHash(parsed.paymentHash)
    }
    return false
  }

  // Check and update payment status for an order
  async function checkAndUpdateOrderPaymentStatus(orderId: string): Promise<boolean> {
    if (isChecking.value) return false

    const order = marketStore.orders[orderId]
    if (!order || !order.paymentRequest) {
      return false
    }

    try {
      isChecking.value = true
      console.log('🔍 Checking payment status for order:', orderId.slice(-8))

      // Method 1: Check by bolt11 (if we can extract payment hash)
      const isPaid = await checkPaymentStatusByBolt11(order.paymentRequest)

      if (isPaid && order.paymentStatus !== 'paid') {
        console.log('✅ Payment confirmed via API check for order:', orderId.slice(-8))
        
        // Update order status
        const updatedOrder = {
          ...order,
          status: 'paid' as const,
          paymentStatus: 'paid' as const,
          paidAt: Math.floor(Date.now() / 1000),
          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
      }

      return isPaid
    } catch (error) {
      console.error('Failed to check payment status:', error)
      return false
    } finally {
      isChecking.value = false
    }
  }

  // Check payment status for all pending orders
  async function checkAllPendingOrders(): Promise<void> {
    const pendingOrders = Object.values(marketStore.orders).filter(
      order => order.paymentStatus === 'pending' && order.paymentRequest
    )

    if (pendingOrders.length === 0) {
      return
    }

    console.log(`🔍 Checking payment status for ${pendingOrders.length} pending orders`)

    for (const order of pendingOrders) {
      await checkAndUpdateOrderPaymentStatus(order.id)
      // Add small delay between requests to avoid overwhelming the API
      await new Promise(resolve => setTimeout(resolve, 100))
    }
  }

  return {
    isChecking,
    checkPaymentStatusByHash,
    checkPaymentStatusByBolt11,
    checkAndUpdateOrderPaymentStatus,
    checkAllPendingOrders
  }
}