<template>
  <form @submit.prevent="submit" class="column" style="gap:10px;">
    <div class="row">
      <label class="toggle" style="flex:0 0 140px;">
        <div class="muted" style="font-size:12px;">VLAN ID</div>
        <input v-model.number="state.id" type="number" min="1" placeholder="e.g. 5" style="width:100%; background:transparent; border:none; outline:none; color:inherit;" required />
      </label>
      <label class="toggle" style="flex:1;">
        <div class="muted" style="font-size:12px;">Nombre</div>
        <input v-model="state.nombre" placeholder="Nombre descriptivo" style="width:100%; background:transparent; border:none; outline:none; color:inherit;" required />
      </label>
    </div>
    <label class="toggle" style="width:100%;">
      <div class="muted" style="font-size:12px;">Descripción</div>
      <textarea v-model="state.descripcion" rows="3" placeholder="Opcional" style="width:100%; background:transparent; border:none; outline:none; color:inherit; resize: vertical;"></textarea>
    </label>
    <div v-if="error" class="muted" style="color:#ff6b6b;">{{ error }}</div>
    <div class="modal-footer">
      <button type="button" class="icon-btn" @click="$emit('cancel')">Cancelar</button>
      <button type="submit" class="icon-btn">Crear</button>
    </div>
  </form>
</template>

<script setup>
import { reactive, ref } from 'vue';

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>

