<script setup lang="ts">
const printers = usePrinters()
const toast = useToast()

const showDrawer = ref(false)
const editingPrinter = ref<typeof printers.printers.value[0] | null>(null)

// Cargar impresoras al montar
onMounted(() => {
  printers.fetchPrinters()
})

function openNewPrinter() {
  editingPrinter.value = null
  showDrawer.value = true
}

function openEditPrinter(printer: typeof printers.printers.value[0]) {
  editingPrinter.value = printer
  showDrawer.value = true
}

async function handleSubmit(data: {
  name: string
  host: string
  deviceId: string
  timeout: number
  isDefault: boolean
}) {
  if (editingPrinter.value) {
    const result = await printers.updatePrinter(editingPrinter.value.id, data)
    if (result) {
      toast.add({ title: 'Impresora actualizada', color: 'success' })
      showDrawer.value = false
    } else {
      toast.add({ title: printers.error.value || 'Error', color: 'error' })
    }
  } else {
    const result = await printers.createPrinter(data)
    if (result) {
      toast.add({ title: 'Impresora agregada', color: 'success' })
      showDrawer.value = false
    } else {
      toast.add({ title: printers.error.value || 'Error', color: 'error' })
    }
  }
}

async function handleSelect(printer: typeof printers.printers.value[0]) {
  await printers.selectPrinter(printer.id)
}

async function handleSetDefault(printer: typeof printers.printers.value[0]) {
  const result = await printers.updatePrinter(printer.id, { isDefault: true })
  if (result) {
    toast.add({ title: 'Impresora predeterminada actualizada', color: 'success' })
  }
}

async function handleDelete(printer: typeof printers.printers.value[0]) {
  if (!confirm(`¿Eliminar la impresora "${printer.name}"?`)) return

  const result = await printers.deletePrinter(printer.id)
  if (result) {
    toast.add({ title: 'Impresora eliminada', color: 'success' })
  } else {
    toast.add({ title: printers.error.value || 'Error', color: 'error' })
  }
}
</script>

<template>
  <div class="space-y-4">
    <div class="flex items-center justify-between">
      <h2 class="text-lg font-semibold text-gray-900 dark:text-white">
        Impresoras
      </h2>
      <UButton
        icon="i-heroicons-plus"
        @click="openNewPrinter"
      >
        Agregar
      </UButton>
    </div>

    <div v-if="printers.loading.value" class="flex justify-center py-8">
      <UIcon name="i-heroicons-arrow-path" class="w-8 h-8 animate-spin text-gray-400" />
    </div>

    <div v-else-if="printers.printers.value.length === 0" class="text-center py-8">
      <UIcon name="i-heroicons-printer" class="w-12 h-12 text-gray-400 mx-auto mb-2" />
      <p class="text-gray-500 dark:text-gray-400">
        No hay impresoras configuradas
      </p>
      <p class="text-sm text-gray-400 dark:text-gray-500 mb-4">
        Agrega una impresora para comenzar a imprimir
      </p>
      <UButton @click="openNewPrinter">
        Agregar primera impresora
      </UButton>
    </div>

    <div v-else class="grid gap-3 sm:grid-cols-2">
      <PrintersCard
        v-for="printer in printers.printers.value"
        :key="printer.id"
        :printer="printer"
        :is-selected="printer.id === printers.selectedPrinterId.value"
        @select="handleSelect(printer)"
        @edit="openEditPrinter(printer)"
        @delete="handleDelete(printer)"
        @set-default="handleSetDefault(printer)"
      />
    </div>

    <UDrawer v-model:open="showDrawer">
      <template #header>
        <h3 class="text-lg font-semibold">
          {{ editingPrinter ? 'Editar impresora' : 'Nueva impresora' }}
        </h3>
      </template>

      <div class="p-4">
        <PrintersForm
          :printer="editingPrinter"
          @submit="handleSubmit"
          @cancel="showDrawer = false"
        />
      </div>
    </UDrawer>
  </div>
</template>
