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

const props = defineProps<{
  printer?: Printer | null
}>()

const emit = defineEmits<{
  submit: [data: {
    name: string
    host: string
    deviceId: string
    timeout: number
    isDefault: boolean
  }]
  cancel: []
}>()

const form = reactive({
  name: props.printer?.name || '',
  host: props.printer?.host || '',
  deviceId: props.printer?.deviceId || '',
  timeout: props.printer?.timeout || 60000,
  isDefault: props.printer?.isDefault || false
})

// Actualizar form cuando cambia el printer
watch(() => props.printer, (newPrinter) => {
  if (newPrinter) {
    form.name = newPrinter.name
    form.host = newPrinter.host
    form.deviceId = newPrinter.deviceId
    form.timeout = newPrinter.timeout
    form.isDefault = newPrinter.isDefault
  } else {
    form.name = ''
    form.host = ''
    form.deviceId = ''
    form.timeout = 60000
    form.isDefault = false
  }
})

function handleSubmit() {
  if (!form.name || !form.host || !form.deviceId) return

  emit('submit', {
    name: form.name,
    host: form.host,
    deviceId: form.deviceId,
    timeout: form.timeout,
    isDefault: form.isDefault
  })
}
</script>

<template>
  <form class="space-y-4" @submit.prevent="handleSubmit">
    <UFormField label="Nombre" required>
      <UInput
        v-model="form.name"
        placeholder="Ej: Impresora Cocina"
        class="w-full"
      />
    </UFormField>

    <UFormField label="Host / IP" required>
      <UInput
        v-model="form.host"
        placeholder="Ej: 192.168.1.100"
        class="w-full"
      />
    </UFormField>

    <UFormField label="Device ID" required>
      <UInput
        v-model="form.deviceId"
        placeholder="Ej: local_printer"
        class="w-full"
      />
    </UFormField>

    <UFormField label="Timeout (ms)">
      <UInput
        v-model.number="form.timeout"
        type="number"
        placeholder="60000"
        class="w-full"
      />
    </UFormField>

    <UCheckbox
      v-model="form.isDefault"
      label="Establecer como impresora predeterminada"
    />

    <div class="flex justify-end gap-2 pt-4">
      <UButton
        type="button"
        color="neutral"
        variant="ghost"
        @click="emit('cancel')"
      >
        Cancelar
      </UButton>
      <UButton
        type="submit"
        :disabled="!form.name || !form.host || !form.deviceId"
      >
        {{ printer ? 'Guardar cambios' : 'Agregar impresora' }}
      </UButton>
    </div>
  </form>
</template>
