<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-[var(--wa-text)]">Nueva Instancia</h3>
            <UButton
              variant="ghost"
              icon="i-lucide-x"
              @click="isOpen = false"
            />
          </div>
        </template>

        <form @submit.prevent="handleSubmit">
          <div class="space-y-4">
            <UFormField label="Nombre de la instancia" required>
              <UInput
                v-model="form.name"
                placeholder="Ej: Ventas, Soporte, Marketing..."
              />
            </UFormField>

            <div class="text-sm text-[var(--wa-text-muted)]">
              <p>Despues de crear la instancia, podras conectarla escaneando un codigo QR con WhatsApp.</p>
            </div>
          </div>

          <div class="flex justify-end gap-3 mt-6">
            <UButton
              type="button"
              variant="ghost"
              @click="isOpen = false"
            >
              Cancelar
            </UButton>
            <UButton
              type="submit"
              :loading="loading"
              :disabled="!form.name.trim()"
            >
              Crear Instancia
            </UButton>
          </div>
        </form>
      </UCard>
    </template>
  </UModal>
</template>

<script setup lang="ts">
const props = defineProps<{
  open: boolean
}>()

const emit = defineEmits<{
  'update:open': [value: boolean]
  created: [instance: any]
}>()

const isOpen = computed({
  get: () => props.open,
  set: (value) => emit('update:open', value)
})

const loading = ref(false)
const form = ref({
  name: ''
})

const handleSubmit = async () => {
  if (!form.value.name.trim()) return

  loading.value = true
  try {
    const instance = await $fetch('/api/instances', {
      method: 'POST',
      body: { name: form.value.name }
    })

    emit('created', instance)
    form.value.name = ''
  } catch (error) {
    console.error('Error creating instance:', error)
    // TODO: Show error toast
  } finally {
    loading.value = false
  }
}
</script>
