<template>
  <LayoutContainer>
    <UiLoadingPanel v-if="pending" />
    <UiForm
      v-else
      :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>
  </LayoutContainer>
</template>

<script setup lang="ts">
import type { PropType } from '@vue/runtime-core'
import ApiModel from '~/models/ApiModel'
import type { AnyJson } from '~/types/data'
import { SUBMIT_TYPE } from '~/types/enum/enums'
import { useRoute } from 'vue-router'
import type { RouteLocationRaw } from 'vue-router'
import { useEntityFetch } from '~/composables/data/useEntityFetch'
import type { AsyncData } from '#app'

const props = defineProps({
  /**
   * Classe de l'ApiModel (ex: Organization, Notification, ...)
   */
  model: {
    type: Function as any as () => typeof ApiModel,
    required: true,
  },
  /**
   * Id de l'objet
   * Si non renseigné, le component essaiera de l'extraire de la route actuelle
   */
  id: {
    type: Number as PropType<number | null>,
    required: false,
    default: null,
  },
  /**
   * Route de retour
   */
  goBackRoute: {
    type: Object as PropType<RouteLocationRaw | null>,
    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 { fetch } = useEntityFetch()
const route = useRoute()
const router = useRouter()

const entityId =
  props.id !== null ? props.id : parseInt(route.params.id as string)

const { data: entity, pending } = fetch(props.model, entityId) as AsyncData<
  ApiModel,
  Error | null
>

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>
