<template>
  <UiForm v-model="entity" :submit-actions="submitActions">
    <template #form.button>
      <v-btn v-if="goBackRoute" class="theme-neutral mr-3" @click="quit">
        {{ $t('cancel') }}
      </v-btn>
    </template>

    <slot v-bind="{ model, entity }" />
  </UiForm>
</template>

<script setup lang="ts" generic="T extends typeof ApiModel">

import type { RouteLocationRaw } from 'vue-router'
import type ApiModel from '~/models/ApiModel'
import type { AnyJson } from '~/types/data'
import { SUBMIT_TYPE } from '~/types/enum/enums'
import { useEntityManager } from '~/composables/data/useEntityManager'

const props = withDefaults(defineProps<{
  model: T
  /**
   * Route de retour
   */
  goBackRoute?: RouteLocationRaw | null
  /**
   * La validation est en cours
   */
  validationPending?: boolean
  /**
   * Faut-il rafraîchir le profil à la soumission du formulaire ?
   */
  refreshProfile?: boolean
}>(), {
  goBackRoute: null,
  validationPending: false,
  refreshProfile: false
})

const router = useRouter()
const { em } = useEntityManager()

const entity = reactive(em.newInstance(props.model)) as InstanceType<T>

const submitActions = computed(() => {
  const actions: AnyJson = {}

  if (props.goBackRoute !== null) {
    actions[SUBMIT_TYPE.SAVE_AND_BACK] = props.goBackRoute
  } else {
    actions[SUBMIT_TYPE.SAVE] = null
  }
  return actions
})

const quit = () => {
  if (!props.goBackRoute) {
    throw new Error('no go back route defined')
  }

  router.push(props.goBackRoute)
}

// Nettoyer les données lors du démontage du composant
onBeforeUnmount(() => {
  // Nettoyer les références du store si nécessaire
  if (process.client) {
    useRepo(props.model).flush()
  }
})
</script>

<style scoped lang="scss"></style>
