<template>
  <div class="space-y-6 p-4">
    <!-- Fetch Blocklist -->
    <div class="space-y-4">
      <h3 class="text-lg font-medium text-[var(--wa-text)]">Obtener Lista de Bloqueados</h3>
      <UButton
        :loading="loadingFetch"
        :disabled="!instanceId"
        @click="fetchBlocklist"
      >
        Obtener Blocklist
      </UButton>
    </div>

    <hr class="border-[var(--wa-border)]" />

    <!-- Block/Unblock -->
    <div class="space-y-4">
      <h3 class="text-lg font-medium text-[var(--wa-text)]">Bloquear / Desbloquear</h3>
      <div class="grid grid-cols-2 gap-4">
        <UInput
          v-model="jid"
          placeholder="JID (ej: 5491155551234@s.whatsapp.net)"
          class="col-span-2"
        />
        <USelectMenu
          v-model="action"
          :items="actionOptions"
          placeholder="Accion"
        />
      </div>
      <UButton
        :loading="loadingUpdate"
        :disabled="!instanceId || !jid || !action"
        @click="updateBlockStatus"
      >
        Ejecutar
      </UButton>
    </div>
  </div>
</template>

<script setup lang="ts">
const props = defineProps<{
  instanceId: string | null
}>()

const emit = defineEmits<{
  (e: 'response', data: any): void
}>()

const jid = ref('')
const action = ref<{ label: string; value: string } | null>(null)
const loadingFetch = ref(false)
const loadingUpdate = ref(false)

const actionOptions = [
  { label: 'Bloquear', value: 'block' },
  { label: 'Desbloquear', value: 'unblock' },
]

const fetchBlocklist = async () => {
  loadingFetch.value = true
  try {
    const result = await $fetch(`/api/debug/blocklist?instanceId=${props.instanceId}`)
    emit('response', result)
  } catch (error: any) {
    emit('response', { success: false, error: error.data?.message || error.message })
  } finally {
    loadingFetch.value = false
  }
}

const updateBlockStatus = async () => {
  if (!action.value) return

  loadingUpdate.value = true
  try {
    const result = await $fetch('/api/debug/blocklist/update', {
      method: 'POST',
      body: {
        instanceId: props.instanceId,
        jid: jid.value,
        action: action.value.value
      }
    })
    emit('response', result)
  } catch (error: any) {
    emit('response', { success: false, error: error.data?.message || error.message })
  } finally {
    loadingUpdate.value = false
  }
}
</script>
