<script setup>
import { reactive, ref } from 'vue';
import { Input, Textarea, Label, Button } from '@/components/ui';

const emit = defineEmits(['success', 'cancel']);
const state = reactive({ id: '', nombre: '', descripcion: '' });
const error = ref('');

async function submit() {
  error.value = '';
  try {
    const res = await fetch('/api/vlans', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id: state.id, nombre: state.nombre, descripcion: state.descripcion })
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok || data.ok === false) {
      error.value = data.error || 'Error al crear VLAN';
      return;
    }
    emit('success', { ...state });
  } catch (e) {
    error.value = String(e?.message || e) || 'Error';
  }
}
</script>

<template>
  <form @submit.prevent="submit" class="flex flex-col gap-3">
    <div class="flex flex-wrap gap-3">
      <div class="w-[140px] space-y-1">
        <Label class="text-xs text-muted">VLAN ID</Label>
        <Input
          v-model.number="state.id"
          type="number"
          min="1"
          placeholder="e.g. 5"
          required
        />
      </div>
      <div class="flex-1 min-w-[140px] space-y-1">
        <Label class="text-xs text-muted">Nombre</Label>
        <Input
          v-model="state.nombre"
          placeholder="Nombre descriptivo"
          required
        />
      </div>
    </div>

    <div class="space-y-1">
      <Label class="text-xs text-muted">Descripción</Label>
      <Textarea
        v-model="state.descripcion"
        :rows="3"
        placeholder="Opcional"
      />
    </div>

    <div v-if="error" class="text-sm text-red-400">{{ error }}</div>

    <div class="flex justify-end gap-2 mt-2">
      <Button type="button" variant="ghost" @click="emit('cancel')">Cancelar</Button>
      <Button type="submit">Crear</Button>
    </div>
  </form>
</template>
