<template>
  <section class="card" style="margin-bottom: 16px;">
    <h2>{{ mode === 'edit' ? t('form.editObjet') : t('form.createObjet') }}</h2>
    <div style="display: grid; gap: 8px;">
      <input v-model="localForm.nom" :placeholder="t('form.nom')" />
      <textarea v-model="localForm.description" rows="3" :placeholder="t('form.description')" />
      <input v-model.number="localForm.quantite" type="number" :placeholder="t('form.quantite')" />
      <select v-model="localForm.statut">
        <option value="en_stock">en_stock</option>
        <option value="pret">pret</option>
        <option value="hors_service">hors_service</option>
        <option value="archive">archive</option>
      </select>
      <div style="display: flex; gap: 8px;">
        <button class="card" type="button" :disabled="saving" @click="emitSave">
          {{ saving ? t('form.saving') : t('form.save') }}
        </button>
        <button class="card" type="button" @click="emitCancel">{{ t('form.cancel') }}</button>
      </div>
      <p v-if="message">{{ message }}</p>
    </div>
  </section>
</template>

<script setup lang="ts">
const { t } = useI18n()

type ObjetFormPayload = {
  nom: string
  description: string
  quantite: number
  statut: string
}

const props = defineProps<{
  modelValue: ObjetFormPayload
  saving: boolean
  mode: 'create' | 'edit'
  message?: string
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: ObjetFormPayload): void
  (e: 'save'): void
  (e: 'cancel'): void
}>()

const localForm = reactive({ ...props.modelValue })

watch(
  () => props.modelValue,
  (value) => {
    Object.assign(localForm, value)
  },
  { deep: true }
)

watch(
  localForm,
  () => emit('update:modelValue', { ...localForm }),
  { deep: true }
)

const emitSave = () => emit('save')
const emitCancel = () => emit('cancel')
</script>
