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

const props = defineProps({ model: { type: Object, required: true } });
const emit = defineEmits(['success', 'cancel']);
const state = reactive({ nombre: '', descripcion: '' });
const error = ref('');

watch(() => props.model, (v) => {
  state.nombre = v?.nombre || '';
  state.descripcion = v?.descripcion || '';
}, { immediate: true, deep: true });

async function submit() {
  error.value = '';
  try {
    const res = await fetch(`/api/devices/${encodeURIComponent(props.model.id)}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ nombre: state.nombre, descripcion: state.descripcion })
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok || data.ok === false) {
      error.value = data.error || 'Error al guardar';
      return;
    }
    emit('success');
  } 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-[180px] space-y-1">
        <Label class="text-xs text-muted">ID (DB)</Label>
        <Input :model-value="model.id" readonly />
      </div>
      <div class="flex-1 min-w-[140px] space-y-1">
        <Label class="text-xs text-muted">MAC</Label>
        <Input :model-value="model.mac" readonly />
      </div>
    </div>

    <div class="space-y-1">
      <Label class="text-xs text-muted">Nombre</Label>
      <Input
        v-model="state.nombre"
        placeholder="Nombre del dispositivo"
      />
    </div>

    <div class="space-y-1">
      <Label class="text-xs text-muted">Descripción</Label>
      <Textarea
        v-model="state.descripcion"
        :rows="3"
        placeholder="Descripción 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">Guardar</Button>
    </div>
  </form>
</template>
