<template>
  <div class="space-y-6 p-4">
    <!-- Get Metadata -->
    <div class="space-y-4">
      <h3 class="text-lg font-medium text-[var(--wa-text)]">Obtener Metadata del Grupo</h3>
      <div class="flex gap-4">
        <UInput
          v-model="metadataJid"
          placeholder="Group JID (ej: 123456789@g.us)"
          class="flex-1"
        />
        <UButton
          :loading="loadingMetadata"
          :disabled="!instanceId || !metadataJid"
          @click="getMetadata"
        >
          Obtener
        </UButton>
      </div>
    </div>

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

    <!-- Get Invite Code -->
    <div class="space-y-4">
      <h3 class="text-lg font-medium text-[var(--wa-text)]">Obtener Codigo de Invitacion</h3>
      <div class="flex gap-4">
        <UInput
          v-model="inviteJid"
          placeholder="Group JID"
          class="flex-1"
        />
        <UButton
          :loading="loadingInvite"
          :disabled="!instanceId || !inviteJid"
          @click="getInviteCode"
        >
          Obtener
        </UButton>
      </div>
    </div>

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

    <!-- Create Group -->
    <div class="space-y-4">
      <h3 class="text-lg font-medium text-[var(--wa-text)]">Crear Grupo</h3>
      <div class="grid grid-cols-2 gap-4">
        <UInput
          v-model="groupName"
          placeholder="Nombre del grupo"
        />
        <UInput
          v-model="groupParticipants"
          placeholder="Participantes (separados por coma)"
        />
      </div>
      <UButton
        :loading="loadingCreate"
        :disabled="!instanceId || !groupName || !groupParticipants"
        @click="createGroup"
      >
        Crear Grupo
      </UButton>
    </div>

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

    <!-- Update Participants -->
    <div class="space-y-4">
      <h3 class="text-lg font-medium text-[var(--wa-text)]">Gestionar Participantes</h3>
      <div class="grid grid-cols-2 gap-4">
        <UInput
          v-model="participantsJid"
          placeholder="Group JID"
        />
        <UInput
          v-model="participantsList"
          placeholder="Participantes (separados por coma)"
        />
        <USelectMenu
          v-model="participantAction"
          :items="participantActions"
          placeholder="Accion"
          class="col-span-2"
        />
      </div>
      <UButton
        :loading="loadingParticipants"
        :disabled="!instanceId || !participantsJid || !participantsList || !participantAction"
        @click="updateParticipants"
      >
        Ejecutar
      </UButton>
    </div>

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

    <!-- Update Subject -->
    <div class="space-y-4">
      <h3 class="text-lg font-medium text-[var(--wa-text)]">Cambiar Nombre del Grupo</h3>
      <div class="grid grid-cols-2 gap-4">
        <UInput
          v-model="subjectJid"
          placeholder="Group JID"
        />
        <UInput
          v-model="newSubject"
          placeholder="Nuevo nombre"
        />
      </div>
      <UButton
        :loading="loadingSubject"
        :disabled="!instanceId || !subjectJid || !newSubject"
        @click="updateSubject"
      >
        Actualizar Nombre
      </UButton>
    </div>

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

    <!-- Update Description -->
    <div class="space-y-4">
      <h3 class="text-lg font-medium text-[var(--wa-text)]">Cambiar Descripcion del Grupo</h3>
      <div class="grid grid-cols-1 gap-4">
        <UInput
          v-model="descriptionJid"
          placeholder="Group JID"
        />
        <UTextarea
          v-model="newDescription"
          placeholder="Nueva descripcion"
          :rows="3"
        />
      </div>
      <UButton
        :loading="loadingDescription"
        :disabled="!instanceId || !descriptionJid"
        @click="updateDescription"
      >
        Actualizar Descripcion
      </UButton>
    </div>
  </div>
</template>

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

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

// Metadata
const metadataJid = ref('')
const loadingMetadata = ref(false)

// Invite
const inviteJid = ref('')
const loadingInvite = ref(false)

// Create
const groupName = ref('')
const groupParticipants = ref('')
const loadingCreate = ref(false)

// Participants
const participantsJid = ref('')
const participantsList = ref('')
const participantAction = ref<{ label: string; value: string } | null>(null)
const loadingParticipants = ref(false)

// Subject
const subjectJid = ref('')
const newSubject = ref('')
const loadingSubject = ref(false)

// Description
const descriptionJid = ref('')
const newDescription = ref('')
const loadingDescription = ref(false)

const participantActions = [
  { label: 'Agregar', value: 'add' },
  { label: 'Remover', value: 'remove' },
  { label: 'Promover a Admin', value: 'promote' },
  { label: 'Degradar a Miembro', value: 'demote' },
]

const getMetadata = async () => {
  loadingMetadata.value = true
  try {
    const result = await $fetch('/api/debug/groups/metadata', {
      method: 'POST',
      body: { instanceId: props.instanceId, jid: metadataJid.value }
    })
    emit('response', result)
  } catch (error: any) {
    emit('response', { success: false, error: error.data?.message || error.message })
  } finally {
    loadingMetadata.value = false
  }
}

const getInviteCode = async () => {
  loadingInvite.value = true
  try {
    const result = await $fetch('/api/debug/groups/invite-code', {
      method: 'POST',
      body: { instanceId: props.instanceId, jid: inviteJid.value }
    })
    emit('response', result)
  } catch (error: any) {
    emit('response', { success: false, error: error.data?.message || error.message })
  } finally {
    loadingInvite.value = false
  }
}

const createGroup = async () => {
  loadingCreate.value = true
  try {
    const participants = groupParticipants.value.split(',').map(p => p.trim()).filter(Boolean)
    const result = await $fetch('/api/debug/groups/create', {
      method: 'POST',
      body: { instanceId: props.instanceId, name: groupName.value, participants }
    })
    emit('response', result)
  } catch (error: any) {
    emit('response', { success: false, error: error.data?.message || error.message })
  } finally {
    loadingCreate.value = false
  }
}

const updateParticipants = async () => {
  if (!participantAction.value) return

  loadingParticipants.value = true
  try {
    const participants = participantsList.value.split(',').map(p => p.trim()).filter(Boolean)
    const result = await $fetch('/api/debug/groups/participants', {
      method: 'POST',
      body: {
        instanceId: props.instanceId,
        jid: participantsJid.value,
        participants,
        action: participantAction.value.value
      }
    })
    emit('response', result)
  } catch (error: any) {
    emit('response', { success: false, error: error.data?.message || error.message })
  } finally {
    loadingParticipants.value = false
  }
}

const updateSubject = async () => {
  loadingSubject.value = true
  try {
    const result = await $fetch('/api/debug/groups/subject', {
      method: 'POST',
      body: { instanceId: props.instanceId, jid: subjectJid.value, subject: newSubject.value }
    })
    emit('response', result)
  } catch (error: any) {
    emit('response', { success: false, error: error.data?.message || error.message })
  } finally {
    loadingSubject.value = false
  }
}

const updateDescription = async () => {
  loadingDescription.value = true
  try {
    const result = await $fetch('/api/debug/groups/description', {
      method: 'POST',
      body: { instanceId: props.instanceId, jid: descriptionJid.value, description: newDescription.value }
    })
    emit('response', result)
  } catch (error: any) {
    emit('response', { success: false, error: error.data?.message || error.message })
  } finally {
    loadingDescription.value = false
  }
}
</script>
