<template>
  <div class="space-y-6 p-4">
    <!-- Chat Modify -->
    <div class="space-y-4">
      <h3 class="text-lg font-medium text-[var(--wa-text)]">Modificar Chat</h3>
      <p class="text-sm text-[var(--wa-text-muted)]">
        Modifica el estado de un chat (archivar, silenciar, marcar como leido, fijar).
      </p>

      <div class="grid grid-cols-2 gap-4">
        <UInput
          v-model="jid"
          placeholder="JID del chat"
          class="col-span-2"
        />
        <USelectMenu
          v-model="modificationType"
          :items="modificationTypes"
          placeholder="Tipo de modificacion"
        />
        <template v-if="modificationType?.value === 'mute'">
          <UInput
            v-model.number="muteTimestamp"
            type="number"
            placeholder="Timestamp de expiracion (0 = unmute)"
          />
        </template>
        <template v-else>
          <USelectMenu
            v-model="boolValue"
            :items="boolOptions"
            placeholder="Valor"
          />
        </template>
      </div>

      <div v-if="requiresLastMessages" class="space-y-2">
        <p class="text-sm text-[var(--wa-text-muted)]">Last Messages (JSON array, requerido para archive/markRead):</p>
        <UTextarea
          v-model="lastMessagesJson"
          placeholder='[{"key": {"remoteJid": "...", "id": "..."}, "messageTimestamp": 123456}]'
          :rows="3"
          class="font-mono text-sm"
        />
      </div>

      <UButton
        :loading="loading"
        :disabled="!instanceId || !jid || !modificationType"
        @click="modifyChat"
      >
        Modificar Chat
      </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 modificationType = ref<{ label: string; value: string } | null>(null)
const boolValue = ref<{ label: string; value: boolean } | null>(null)
const muteTimestamp = ref<number>(0)
const lastMessagesJson = ref('')
const loading = ref(false)

const modificationTypes = [
  { label: 'Archivar', value: 'archive' },
  { label: 'Silenciar', value: 'mute' },
  { label: 'Marcar Leido', value: 'markRead' },
  { label: 'Fijar', value: 'pin' },
]

const boolOptions = [
  { label: 'Activar (true)', value: true },
  { label: 'Desactivar (false)', value: false },
]

const requiresLastMessages = computed(() =>
  modificationType.value?.value === 'archive' || modificationType.value?.value === 'markRead'
)

const modifyChat = async () => {
  if (!modificationType.value) return

  loading.value = true
  try {
    let value: boolean | number | null
    let lastMessages: any[] = []

    if (modificationType.value.value === 'mute') {
      value = muteTimestamp.value || null
    } else {
      value = boolValue.value?.value ?? false
    }

    if (requiresLastMessages.value && lastMessagesJson.value.trim()) {
      try {
        lastMessages = JSON.parse(lastMessagesJson.value)
      } catch {
        emit('response', { success: false, error: 'Invalid JSON for lastMessages' })
        loading.value = false
        return
      }
    }

    const result = await $fetch('/api/debug/chat/modify', {
      method: 'POST',
      body: {
        instanceId: props.instanceId,
        jid: jid.value,
        type: modificationType.value.value,
        value,
        lastMessages
      }
    })
    emit('response', result)
  } catch (error: any) {
    emit('response', { success: false, error: error.data?.message || error.message })
  } finally {
    loading.value = false
  }
}
</script>
