<template>
  <div class="bg-white border rounded-lg p-6">
    <div class="flex items-center justify-between mb-4">
      <h3 class="text-lg font-semibold text-gray-900">Payment</h3>
      <Badge :variant="getPaymentStatusVariant(paymentStatus)">
        {{ formatPaymentStatus(paymentStatus) }}
      </Badge>
    </div>

    <!-- Invoice Information -->
    <div v-if="invoice" class="space-y-4">
      <!-- Amount and Status -->
      <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
        <div>
          <p class="text-sm text-gray-600">Amount</p>
          <p class="text-2xl font-bold text-gray-900">
            {{ invoice.amount }} {{ currency }}
          </p>
        </div>
        <div class="text-right">
          <p class="text-sm text-gray-600">Status</p>
          <p class="text-lg font-semibold" :class="getStatusColor(paymentStatus)">
            {{ formatPaymentStatus(paymentStatus) }}
          </p>
        </div>
      </div>

      <!-- Lightning Invoice QR Code -->
      <div class="text-center">
        <div class="mb-4">
          <h4 class="font-medium text-gray-900 mb-2">Lightning Invoice</h4>
          <p class="text-sm text-gray-600">Scan with your Lightning wallet to pay</p>
        </div>
        
        <!-- QR Code -->
        <div class="w-48 h-48 mx-auto mb-4">
          <div v-if="qrCodeDataUrl && !qrCodeError" class="w-full h-full">
            <img 
              :src="qrCodeDataUrl" 
              :alt="`QR Code for ${invoice.amount} ${currency} payment`"
              class="w-full h-full border border-gray-200 rounded-lg"
            />
          </div>
          <div v-else-if="qrCodeLoading" class="w-full h-full bg-gray-100 rounded-lg flex items-center justify-center">
            <div class="text-center text-gray-500">
              <div class="text-4xl mb-2 animate-pulse">⚡</div>
              <div class="text-sm">Generating QR...</div>
            </div>
          </div>
          <div v-else-if="qrCodeError" class="w-full h-full bg-red-50 border border-red-200 rounded-lg flex items-center justify-center">
            <div class="text-center text-red-500">
              <div class="text-4xl mb-2">⚠️</div>
              <div class="text-sm">{{ qrCodeError }}</div>
              <Button 
                @click="retryQRCode" 
                variant="outline" 
                size="sm" 
                class="mt-2"
              >
                Retry
              </Button>
            </div>
          </div>
          <div v-else class="w-full h-full bg-gray-100 rounded-lg flex items-center justify-center">
            <div class="text-center text-gray-500">
              <div class="text-4xl mb-2">⚡</div>
              <div class="text-sm">No invoice</div>
            </div>
          </div>
        </div>

        <!-- QR Code Actions -->
        <div v-if="qrCodeDataUrl && !qrCodeError" class="mb-4">
          <Button
            @click="downloadQRCode"
            variant="outline"
            size="sm"
            class="w-full"
          >
            <Download class="w-4 h-4 mr-2" />
            Download QR Code
          </Button>
        </div>

        <!-- Payment Request -->
        <div class="mb-4">
          <label class="block text-sm font-medium text-gray-700 mb-2">
            Payment Request
          </label>
          <div class="flex items-center gap-2">
            <Input
              :value="invoice.bolt11"
              readonly
              class="flex-1 font-mono text-sm"
            />
            <Button
              @click="copyPaymentRequest"
              variant="outline"
              size="sm"
            >
              <Copy class="w-4 h-4" />
            </Button>
          </div>
        </div>

        <!-- Copy to Wallet Button -->
        <Button
          @click="openInWallet"
          variant="default"
          class="w-full"
        >
          <Wallet class="w-4 h-4 mr-2" />
          Open in Lightning Wallet
        </Button>
      </div>

      <!-- Payment Details -->
      <div class="border-t pt-4">
        <h4 class="font-medium text-gray-900 mb-3">Payment Details</h4>
        <div class="space-y-2 text-sm">
          <div class="flex justify-between">
            <span class="text-gray-600">Payment Hash:</span>
            <span class="font-mono text-gray-900">{{ formatHash(invoice.payment_hash) }}</span>
          </div>
          <div class="flex justify-between">
            <span class="text-gray-600">Created:</span>
            <span class="text-gray-900">{{ formatDate(invoice.created_at ? new Date(invoice.created_at).getTime() : Date.now()) }}</span>
          </div>
          <div class="flex justify-between">
            <span class="text-gray-600">Expires:</span>
            <span class="text-gray-900">{{ formatDate(invoice.expiry ? new Date(invoice.expiry).getTime() : Date.now()) }}</span>
          </div>
          <div v-if="paidAt" class="flex justify-between">
            <span class="text-gray-600">Paid At:</span>
            <span class="text-gray-900">{{ formatDate(paidAt) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- No Invoice State -->
    <div v-else class="text-center py-8">
      <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
        <Wallet class="w-8 h-8 text-gray-400" />
      </div>
      <h4 class="text-lg font-medium text-gray-900 mb-2">No Payment Invoice</h4>
      <p class="text-gray-600 mb-4">
        A Lightning invoice will be sent by the merchant once they process your order.
      </p>
      <p class="text-sm text-gray-500">
        You'll receive the invoice via Nostr when it's ready.
      </p>
    </div>

    <!-- Payment Instructions -->
    <div v-if="paymentStatus === 'pending'" class="mt-6 p-4 bg-muted/50 border border-border rounded-lg">
      <div class="flex items-start space-x-3">
        <div class="w-5 h-5 bg-muted rounded-full flex items-center justify-center mt-0.5">
          <Info class="w-3 h-3 text-muted-foreground" />
        </div>
        <div class="text-sm text-muted-foreground">
          <h5 class="font-medium mb-1 text-foreground">Payment Instructions</h5>
          <ul class="space-y-1">
            <li>• Use a Lightning-compatible wallet (e.g., Phoenix, Breez, Alby)</li>
            <li>• Scan the QR code or copy the payment request</li>
            <li>• Confirm the payment amount and send</li>
            <li>• Your order will be processed once payment is confirmed</li>
          </ul>
        </div>
      </div>
    </div>

    <!-- Payment Success -->
    <div v-if="paymentStatus === 'paid'" class="mt-6 p-4 bg-green-50 border border-green-200 rounded-lg">
      <div class="flex items-center space-x-3">
        <div class="w-5 h-5 bg-green-100 rounded-full flex items-center justify-center">
          <CheckCircle class="w-3 h-3 text-green-600" />
        </div>
        <div class="text-sm text-green-800">
          <h5 class="font-medium">Payment Confirmed!</h5>
          <p>Your order is being processed. You'll receive updates via Nostr.</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { 
  Copy, 
  Wallet, 
 
  Info, 
  CheckCircle,
  Download
} from 'lucide-vue-next'
import { useMarketStore } from '@/stores/market'
import QRCode from 'qrcode'


interface Props {
  orderId: string
}

const props = defineProps<Props>()
const marketStore = useMarketStore()

// Computed properties
const order = computed(() => marketStore.orders[props.orderId])
const invoice = computed(() => order.value?.lightningInvoice)
const paymentStatus = computed(() => order.value?.paymentStatus || 'pending')
const currency = computed(() => order.value?.currency || 'sat')
const paidAt = computed(() => order.value?.paidAt)

// QR Code generation
const qrCodeDataUrl = ref<string | null>(null)
const qrCodeLoading = ref(false)
const qrCodeError = ref<string | null>(null)

const generateQRCode = async (paymentRequest: string) => {
  try {
    qrCodeLoading.value = true
    qrCodeError.value = null
    
    const dataUrl = await QRCode.toDataURL(paymentRequest, {
      width: 192, // 48 * 4 for high DPI displays
      margin: 2,
      color: {
        dark: '#000000',
        light: '#FFFFFF'
      }
    })
    qrCodeDataUrl.value = dataUrl
  } catch (error) {
    console.error('Failed to generate QR code:', error)
    qrCodeError.value = 'Failed to generate QR code'
    qrCodeDataUrl.value = null
  } finally {
    qrCodeLoading.value = false
  }
}

// Methods
const getPaymentStatusVariant = (status: string) => {
  switch (status) {
    case 'paid': return 'default'
    case 'pending': return 'secondary'
    case 'expired': return 'destructive'
    default: return 'outline'
  }
}

const formatPaymentStatus = (status: string) => {
  switch (status) {
    case 'paid': return 'Paid'
    case 'pending': return 'Pending'
    case 'expired': return 'Expired'
    default: return 'Unknown'
  }
}

const getStatusColor = (status: string) => {
  switch (status) {
    case 'paid': return 'text-green-600'
    case 'pending': return 'text-yellow-600'
    case 'expired': return 'text-red-600'
    default: return 'text-gray-600'
  }
}

const formatHash = (hash: string) => {
  if (!hash) return 'N/A'
  return `${hash.substring(0, 8)}...${hash.substring(hash.length - 8)}`
}

const formatDate = (timestamp: number) => {
  if (!timestamp) return 'N/A'
  return new Date(timestamp * 1000).toLocaleString()
}

const copyPaymentRequest = async () => {
  if (!invoice.value?.bolt11) return
  
  try {
    await navigator.clipboard.writeText(invoice.value.bolt11)
    // TODO: Show toast notification
    console.log('Payment request copied to clipboard')
  } catch (error) {
    console.error('Failed to copy payment request:', error)
  }
}

const openInWallet = () => {
  if (!invoice.value?.bolt11) return
  
  // Open in Lightning wallet
  const walletUrl = `lightning:${invoice.value.bolt11}`
  window.open(walletUrl, '_blank')
}

const downloadQRCode = () => {
  if (!qrCodeDataUrl.value) return

  const link = document.createElement('a')
  link.href = qrCodeDataUrl.value
  link.download = `qr-code-${invoice.value?.amount}-${currency.value}.png`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const retryQRCode = () => {
  if (invoice.value?.bolt11) {
    generateQRCode(invoice.value.bolt11)
  }
}

// Lifecycle
onMounted(() => {
  // Set up payment monitoring if invoice exists
  if (invoice.value && props.orderId) {
    // Payment monitoring is handled by the market store
    console.log('Payment display mounted for order:', props.orderId)
    
    // Generate QR code for the invoice
    if (invoice.value.bolt11) {
      generateQRCode(invoice.value.bolt11)
    }
  }
})

// Watch for invoice changes to regenerate QR code
watch(() => invoice.value?.bolt11, (newPaymentRequest) => {
  if (newPaymentRequest) {
    generateQRCode(newPaymentRequest)
  } else {
    qrCodeDataUrl.value = null
  }
}, { immediate: true })
</script>
