<template>
  <BContainer
    fluid
    class="p-0"
  >
    <CrudHeader :title="$route.meta.label">
      <template #menu>
        <div>
          <BButton
            variant="secondary"
            @click="doBack"
            >Retour</BButton
          >
          <BButton
            variant="primary"
            @click="doSave"
            >Enregistrer</BButton
          >
        </div>
      </template>
      <template #bottom> </template>
    </CrudHeader>

    <BForm
      v-if="form !== null"
      class="p-3"
      @submit="submit"
    >
      <BAlert
        v-if="form?.error"
        dismissible
        variant="warning"
        :model-value="true"
      >
        <div v-html="form.error"></div>
      </BAlert>
      <BRow>
        <BCol>
          <FormView :form="form" />
        </BCol>
      </BRow>
    </BForm>
  </BContainer>
</template>

<script setup>
import { BContainer, BButton, BForm, BRow, BCol, BAlert } from 'bootstrap-vue-next'
import CrudHeader from '../../components/crud/CrudHeader.vue'
import FormView from '../../components/crud/FormView.vue'
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { create, createForm } from '../../models/user'
import { requestErrorBuilder } from '../../lib/request'

const router = useRouter()
const parentRouteName = 'users'
const form = ref(null)

const doSave = () => {
  create(
    form.value.data,
    (data) => {
      if (data.code === 400) {
        form.value.error = requestErrorBuilder(data)
      } else {
        doBack()
      }
    },
    (err) => {
      form.value.error = `Une erreur s'est produite : ${err}`
    },
  )
}

const doBack = () => {
  router.replace({ name: parentRouteName })
}

onMounted(() => {
  form.value = createForm()
})
</script>
