<template>
  <UModal v-model:open="isOpen" :ui="{ width: 'max-w-md' }">
    <template #content>
      <UCard>
        <template #header>
          <div class="flex items-center justify-between">
            <h3 class="text-lg font-semibold text-[var(--wa-text)]">Escanear Codigo QR</h3>
            <UButton
              variant="ghost"
              icon="i-lucide-x"
              @click="isOpen = false"
            />
          </div>
        </template>

        <div class="text-center">
          <!-- QR Code Display -->
          <div v-if="qrCode" class="mb-4">
            <div class="bg-white p-4 rounded-lg inline-block">
              <img :src="qrCode" alt="QR Code" class="w-64 h-64" />
            </div>
          </div>

          <div v-else class="mb-4 py-16">
            <UIcon
              name="i-lucide-loader-2"
              class="w-12 h-12 text-[var(--wa-text-muted)] animate-spin mx-auto"
            />
            <p class="text-[var(--wa-text-muted)] mt-4">Generando codigo QR...</p>
          </div>

          <!-- Instructions -->
          <div class="text-sm text-[var(--wa-text-muted)] space-y-2">
            <p>1. Abre WhatsApp en tu telefono</p>
            <p>2. Ve a Configuracion > Dispositivos vinculados</p>
            <p>3. Toca "Vincular un dispositivo"</p>
            <p>4. Escanea este codigo QR</p>
          </div>

          <!-- Alternative: Pairing Code -->
          <div class="mt-6 pt-6 border-t border-[var(--wa-border)]">
            <p class="text-sm text-[var(--wa-text-muted)] mb-3">
              O usa un codigo de emparejamiento
            </p>
            <UButton
              variant="soft"
              @click="requestPairingCode"
              :loading="loadingPairing"
            >
              Obtener Codigo
            </UButton>

            <div v-if="pairingCode" class="mt-4">
              <p class="text-2xl font-mono font-bold text-[var(--wa-green-light)] tracking-widest">
                {{ pairingCode }}
              </p>
              <p class="text-xs text-[var(--wa-text-muted)] mt-2">
                Ingresa este codigo en WhatsApp > Dispositivos vinculados > Vincular con numero de telefono
              </p>
            </div>
          </div>
        </div>
      </UCard>
    </template>
  </UModal>
</template>

<script setup lang="ts">
interface Props {
  open: boolean
  instanceId: string | null
  qrCode: string | null
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:open': [value: boolean]
}>()

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

const loadingPairing = ref(false)
const pairingCode = ref<string | null>(null)

const requestPairingCode = async () => {
  if (!props.instanceId) return

  loadingPairing.value = true
  try {
    const response = await $fetch<{ code: string }>(`/api/instances/${props.instanceId}/pairing-code`, {
      method: 'POST'
    })
    pairingCode.value = response.code
  } catch (error) {
    console.error('Error requesting pairing code:', error)
  } finally {
    loadingPairing.value = false
  }
}

// Reset pairing code when modal closes
watch(isOpen, (value) => {
  if (!value) {
    pairingCode.value = null
  }
})
</script>
