<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-white">Editar Alias</h3>
            <UButton
              variant="ghost"
              icon="i-lucide-x"
              size="sm"
              @click="isOpen = false"
            />
          </div>
        </template>

        <div class="space-y-4">
          <p class="text-sm text-[var(--wa-text-muted)]">
            Asigna un nombre personalizado a este chat. El alias tiene prioridad sobre el nombre de WhatsApp.
          </p>

          <UFormField label="Alias">
            <UInput
              v-model="aliasValue"
              placeholder="Nombre personalizado (dejar vacio para usar nombre original)"
              icon="i-lucide-pencil"
              size="lg"
            />
          </UFormField>

          <div v-if="chat" class="p-3 rounded-lg bg-[var(--wa-bg-light)]">
            <p class="text-xs text-[var(--wa-text-muted)] mb-1">Nombre original:</p>
            <p class="text-sm text-white">{{ chat.originalName || chat.jid }}</p>
          </div>
        </div>

        <template #footer>
          <div class="flex justify-between gap-2">
            <UButton
              v-if="aliasValue"
              variant="ghost"
              color="error"
              icon="i-lucide-trash-2"
              @click="clearAlias"
            >
              Quitar alias
            </UButton>
            <div class="flex-1" />
            <UButton variant="ghost" @click="isOpen = false">
              Cancelar
            </UButton>
            <UButton
              :loading="isSaving"
              @click="handleSave"
            >
              Guardar
            </UButton>
          </div>
        </template>
      </UCard>
    </template>
  </UModal>
</template>

<script setup lang="ts">
interface Chat {
  id: string
  jid: string
  name: string
  alias?: string | null
  originalName?: string
  isGroup?: boolean
}

const props = defineProps<{
  chat: Chat | null
  instanceId: string
}>()

const isOpen = defineModel<boolean>('open', { default: false })

const emit = defineEmits<{
  saved: [chat: Chat]
}>()

const isSaving = ref(false)
const aliasValue = ref('')

const clearAlias = () => {
  aliasValue.value = ''
}

const handleSave = async () => {
  if (!props.chat || !props.instanceId) return

  isSaving.value = true
  try {
    const response = await $fetch(`/api/messages/${props.instanceId}/${props.chat.id}/alias`, {
      method: 'PUT',
      body: {
        alias: aliasValue.value.trim() || null
      }
    })

    if (response.success) {
      emit('saved', {
        ...props.chat,
        alias: response.chat.alias,
        name: response.chat.alias || props.chat.originalName || props.chat.name
      })
      isOpen.value = false
    }
  } catch (error) {
    console.error('Error saving alias:', error)
  } finally {
    isSaving.value = false
  }
}

// Initialize alias when modal opens or chat changes
watch([isOpen, () => props.chat], ([open, chat]) => {
  if (open && chat) {
    aliasValue.value = chat.alias || ''
  }
}, { immediate: true })
</script>
