<template>
  <UModal v-model:open="isOpen">
    <template #content>
      <UCard>
        <template #header>
          <div class="flex items-center justify-between">
            <h3 class="text-lg font-semibold text-[var(--wa-text)]">
              {{ webhook ? 'Editar Webhook' : 'Nuevo Webhook' }}
            </h3>
            <UButton
              variant="ghost"
              icon="i-lucide-x"
              @click="isOpen = false"
            />
          </div>
        </template>

        <form @submit.prevent="handleSubmit">
          <div class="space-y-4">
            <UFormField label="Nombre" required>
              <UInput
                v-model="form.name"
                placeholder="Ej: Notificaciones a n8n"
              />
            </UFormField>

            <UFormField label="URL" required>
              <UInput
                v-model="form.url"
                placeholder="https://..."
                type="url"
              />
            </UFormField>

            <UFormField label="Secret (opcional)">
              <UInput
                v-model="form.secret"
                placeholder="Para firmar las peticiones con HMAC"
                type="password"
              />
            </UFormField>

            <UFormField label="Eventos">
              <div class="grid grid-cols-2 gap-2">
                <label
                  v-for="event in availableEvents"
                  :key="event.value"
                  class="flex items-center gap-2 cursor-pointer text-sm text-[var(--wa-text)]"
                >
                  <input
                    type="checkbox"
                    :checked="form.events.includes(event.value)"
                    @change="toggleEvent(event.value)"
                    class="w-4 h-4 rounded border-gray-600 bg-gray-700 text-[var(--wa-green-light)] focus:ring-[var(--wa-green-light)] focus:ring-offset-0"
                  />
                  {{ event.label }}
                </label>
              </div>
            </UFormField>

            <UFormField label="Instancia">
              <USelectMenu
                v-model="form.instanceId"
                :items="instanceOptions"
                placeholder="Todas las instancias"
              />
            </UFormField>
          </div>

          <div class="flex justify-end gap-3 mt-6">
            <UButton
              type="button"
              variant="ghost"
              @click="isOpen = false"
            >
              Cancelar
            </UButton>
            <UButton
              type="submit"
              :loading="loading"
              :disabled="!isValid"
            >
              {{ webhook ? 'Guardar Cambios' : 'Crear Webhook' }}
            </UButton>
          </div>
        </form>
      </UCard>
    </template>
  </UModal>
</template>

<script setup lang="ts">
interface Webhook {
  id: string
  name: string
  url: string
  secret?: string
  events: string[]
  instanceId?: string
}

interface Instance {
  id: string
  name: string
}

interface Props {
  open: boolean
  webhook?: Webhook | null
  instances?: Instance[]
}

const props = defineProps<Props>()

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

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

const loading = ref(false)

const form = ref({
  name: '',
  url: '',
  secret: '',
  events: [] as string[],
  instanceId: null as string | null
})

const availableEvents = [
  { value: 'message.received', label: 'Mensaje recibido' },
  { value: 'message.sent', label: 'Mensaje enviado' },
  { value: 'message.status', label: 'Estado de mensaje' },
  { value: 'instance.connected', label: 'Instancia conectada' },
  { value: 'instance.disconnected', label: 'Instancia desconectada' },
  { value: 'instance.qr', label: 'QR disponible' }
]

// Instance options for selector
const instanceOptions = computed(() => [
  { label: 'Todas las instancias', value: null },
  ...(props.instances || []).map(i => ({ label: i.name, value: i.id }))
])

const isValid = computed(() => {
  return form.value.name.trim() && form.value.url.trim() && form.value.events.length > 0
})

const toggleEvent = (eventValue: string) => {
  const index = form.value.events.indexOf(eventValue)
  if (index === -1) {
    form.value.events.push(eventValue)
  } else {
    form.value.events.splice(index, 1)
  }
}

// Watch for webhook changes to populate form
watch(() => props.webhook, (webhook) => {
  if (webhook) {
    form.value = {
      name: webhook.name,
      url: webhook.url,
      secret: webhook.secret || '',
      events: [...webhook.events],
      instanceId: webhook.instanceId || null
    }
  } else {
    form.value = {
      name: '',
      url: '',
      secret: '',
      events: [],
      instanceId: null
    }
  }
}, { immediate: true })

const handleSubmit = async () => {
  if (!isValid.value) return

  loading.value = true
  try {
    const method = props.webhook ? 'PUT' : 'POST'
    const url = props.webhook
      ? `/api/webhooks/${props.webhook.id}`
      : '/api/webhooks'

    const result = await $fetch(url, {
      method,
      body: form.value
    })

    emit('saved', result)
  } catch (error) {
    console.error('Error saving webhook:', error)
  } finally {
    loading.value = false
  }
}
</script>
