<template>
  <section class="card" style="margin-bottom: 16px;">
    <h2>{{ mode === 'edit' ? t('form.editCategorie') : t('form.createCategorie') }}</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.slug" :placeholder="t('form.slug')" />
      <input v-model="localForm.icone" :placeholder="t('form.icone')" />
      <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 CategorieFormPayload = {
  nom: string
  parent_id: string
  slug: string
  icone: string
}

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

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