<script setup lang="ts">
import type { PrintTemplate } from '~/composables/useTemplates'

const props = defineProps<{
  template: PrintTemplate | null
  open: boolean
}>()

const emit = defineEmits<{
  'update:open': [value: boolean]
  load: [values: Record<string, string>]
}>()

const values = ref<Record<string, string>>({})

// Inicializar con valores por defecto cuando cambia el template
watch(() => props.template, (t) => {
  if (t) {
    values.value = {}
    for (const v of t.variables || []) {
      values.value[v.name] = v.defaultValue || ''
    }
  }
}, { immediate: true })

function handleLoad() {
  emit('load', { ...values.value })
}

function handleDrawerUpdate(value: boolean) {
  emit('update:open', value)
}

function handleClose() {
  emit('update:open', false)
}

// Validar que todos los campos requeridos estén completos
const canLoad = computed(() => {
  if (!props.template?.variables) return false
  return props.template.variables.every(v => values.value[v.name]?.trim())
})
</script>

<template>
  <UDrawer
    :open="open"
    direction="bottom"
    title="Completar variables"
    description="Ingresa los valores para las variables del template"
    @update:open="handleDrawerUpdate"
  >
    <template #body>
      <div class="space-y-4 p-4">
        <p class="text-sm text-gray-500 dark:text-gray-400">
          Template: <strong>{{ template?.name }}</strong>
        </p>

        <UFormField
          v-for="v in template?.variables || []"
          :key="v.name"
          :label="v.label || v.name"
          required
        >
          <UInput
            v-model="values[v.name]"
            :placeholder="v.defaultValue || `Ingrese ${v.label || v.name}`"
          />
        </UFormField>
      </div>
    </template>

    <template #footer>
      <div class="flex gap-2 justify-end p-4">
        <UButton variant="ghost" @click="handleClose">
          Cancelar
        </UButton>
        <UButton
          color="primary"
          :disabled="!canLoad"
          @click="handleLoad"
        >
          Cargar en cola
        </UButton>
      </div>
    </template>
  </UDrawer>
</template>
