<template>
  <UiForm :model="model" :entity="entity" :submitActions="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">
import type { PropType } from '@vue/runtime-core'
import type { RouteLocationRaw } from '@intlify/vue-router-bridge'
import 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 = defineProps({
  /**
   * Classe de l'ApiModel (ex: Organization, Notification, ...)
   */
  model: {
    type: Function as any as () => typeof ApiModel,
    required: true,
  },
  /**
   * Route de retour
   */
  goBackRoute: {
    type: Object as PropType<RouteLocationRaw>,
    required: false,
    default: null,
  },
  /**
   * La validation est en cours
   */
  validationPending: {
    type: Boolean,
    required: false,
    default: false,
  },
  /**
   * Faut-il rafraichir le profil à la soumission du formulaire ?
   */
  refreshProfile: {
    type: Boolean,
    required: false,
    default: false,
  },
})

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

//@ts-ignore Pour une raison que j'ignore, le type Ref<ApiModel> met en erreur la prop entity de UiForm...
const entity: ApiModel = reactive(em.newInstance(props.model))

const submitActions = computed(() => {
  let 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 Error('no go back route defined')
  }

  router.push(props.goBackRoute)
}
</script>

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