<template>
  <UModal v-model="isOpen">
    <UCard class="max-w-md">
      <template #header>
        <h3 class="text-lg font-semibold">QR Code</h3>
        <p class="text-sm text-gray-600 mt-1">{{ title }}</p>
      </template>

      <div class="text-center space-y-4">
        <div class="bg-white p-4 rounded-lg inline-block">
          <canvas ref="qrCanvas"></canvas>
        </div>

        <div class="space-y-2">
          <p class="text-sm text-gray-600">
            <strong>URL:</strong>
            <span class="font-mono text-xs break-all">{{ fullUrl }}</span>
          </p>
          <UButton
            @click="downloadQR"
            variant="outline"
            size="sm"
            icon="i-heroicons-arrow-down-tray"
          >
            Download QR Code
          </UButton>
        </div>
      </div>
    </UCard>
  </UModal>
</template>

<script setup lang="ts">
import QRCode from 'qrcode'

interface Props {
  modelValue: boolean
  url: string
  title?: string
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const isOpen = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const qrCanvas = ref<HTMLCanvasElement>()
const fullUrl = computed(() => {
  if (process.client) {
    return `${window.location.origin}${props.url}`
  }
  return props.url
})

const generateQR = async () => {
  if (!qrCanvas.value) return

  try {
    await QRCode.toCanvas(qrCanvas.value, fullUrl.value, {
      width: 200,
      margin: 2,
      color: {
        dark: '#1f2937',
        light: '#ffffff'
      }
    })
  } catch (error) {
    console.error('Failed to generate QR code:', error)
  }
}

const downloadQR = () => {
  if (!qrCanvas.value) return

  const link = document.createElement('a')
  link.download = `sermon-qr-${props.title || 'code'}.png`
  link.href = qrCanvas.value.toDataURL()
  link.click()
}

watch(isOpen, (open) => {
  if (open) {
    nextTick(() => {
      generateQR()
    })
  }
})
</script>
