<template>
  <div class="instance-card p-6">
    <div class="flex items-start justify-between mb-4">
      <div class="flex items-center gap-3">
        <div
          class="w-10 h-10 rounded-lg flex items-center justify-center"
          :class="webhook.isActive ? 'bg-green-500/20' : 'bg-gray-500/20'"
        >
          <UIcon
            name="i-lucide-webhook"
            class="w-5 h-5"
            :class="webhook.isActive ? 'text-green-500' : 'text-gray-500'"
          />
        </div>
        <div>
          <h3 class="font-semibold text-[var(--wa-text)]">{{ webhook.name }}</h3>
          <p class="text-sm text-[var(--wa-text-muted)] truncate max-w-md">{{ webhook.url }}</p>
        </div>
      </div>

      <USwitch
        :model-value="webhook.isActive"
        @update:model-value="$emit('toggle', webhook.id, $event)"
      />
    </div>

    <!-- Events -->
    <div class="mb-4">
      <p class="text-xs text-[var(--wa-text-muted)] mb-2">Eventos:</p>
      <div class="flex flex-wrap gap-1">
        <span
          v-for="event in webhook.events"
          :key="event"
          class="bg-[var(--wa-bg-light)] text-[var(--wa-text-muted)] text-xs px-2 py-1 rounded"
        >
          {{ event }}
        </span>
      </div>
    </div>

    <!-- Instance -->
    <div v-if="webhook.instanceId" class="mb-4">
      <p class="text-xs text-[var(--wa-text-muted)]">
        Instancia: <span class="text-[var(--wa-text)]">{{ webhook.instanceName || webhook.instanceId }}</span>
      </p>
    </div>
    <div v-else class="mb-4">
      <p class="text-xs text-[var(--wa-text-muted)]">
        Aplica a: <span class="text-[var(--wa-green-light)]">Todas las instancias</span>
      </p>
    </div>

    <!-- Actions -->
    <div class="flex items-center gap-2">
      <UButton
        size="sm"
        variant="soft"
        icon="i-lucide-play"
        @click="$emit('test', webhook.id)"
      >
        Probar
      </UButton>
      <UButton
        size="sm"
        variant="ghost"
        icon="i-lucide-pencil"
        @click="$emit('edit', webhook)"
      >
        Editar
      </UButton>
      <UButton
        size="sm"
        variant="ghost"
        color="red"
        icon="i-lucide-trash-2"
        @click="$emit('delete', webhook.id)"
      >
        Eliminar
      </UButton>
    </div>
  </div>
</template>

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

interface Props {
  webhook: Webhook
}

defineProps<Props>()

defineEmits<{
  edit: [webhook: Webhook]
  delete: [webhookId: string]
  test: [webhookId: string]
  toggle: [webhookId: string, active: boolean]
}>()
</script>
