<template>
  <section class="card" style="margin-bottom: 16px;">
    <h2>{{ mode === 'edit' ? t('form.editEmplacement') : t('form.createEmplacement') }}</h2>
    <div style="display: grid; gap: 8px;">
      <input v-model="localForm.nom" :placeholder="t('form.nom')" />
      <input v-model="localForm.parent_id" :placeholder="t('form.parentIdOpt')" />
      <input v-model="localForm.piece" :placeholder="t('form.piece')" />
      <input v-model="localForm.meuble" :placeholder="t('form.meuble')" />
      <input v-model="localForm.numero_boite" :placeholder="t('form.numeroBoite')" />
      <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 EmplacementFormPayload = {
  nom: string
  parent_id: string
  piece: string
  meuble: string
  numero_boite: string
}

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

const emit = defineEmits<{
  (e: 'update:modelValue', value: EmplacementFormPayload): 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>
