<template>
  <UiInputTreeSelect
    :model-value="modelValue"
    :items="content"
    :label="$t(label)"
    v-bind="$attrs"
    :loading="status === FETCHING_STATUS.PENDING"
    :max-visible-chips="maxVisibleChips"
    :nb-level="nbLevel"
    @update:model-value="$emit('update:modelValue', $event)"
  />
</template>

<script setup lang="ts">
import { useEntityFetch } from '~/composables/data/useEntityFetch'
import { FETCHING_STATUS } from '~/types/enum/data'
import type { PropType } from 'vue'
import type ApiResource from '~/models/ApiResource'
import { useI18nUtils } from '~/composables/utils/useI18nUtils'
import ArrayUtils from '~/services/utils/arrayUtils'

const props = defineProps({
  modelValue: {
    type: Array as PropType<string[]>,
    required: true,
  },
  /**
   * ResourceTree qui sera fetch
   */
  model: {
    type: Object as PropType<typeof ApiResource>,
    required: true,
  },
  /**
   * Label du champ
   * Si non défini, c'est le nom de propriété qui est utilisé
   */
  label: {
    type: String,
    required: false,
    default: null,
  },
  /**
   * Si true, traduit les items du ResourceTree
   */
  translate: {
    type: Boolean,
    default: true,
  },
  /**
   * Si true, trie les items du ResourceTree par ordre alphabétique
   */
  sort: {
    type: Boolean,
    default: false,
  },
  /**
   * Nombre de puces maximum à afficher
   */
  maxVisibleChips: {
    type: Number,
    required: false,
    default: 6,
  },
  // TODO: revoir si nécessaire
  nbLevel: {
    type: Number,
    required: false,
    default: 3,
    validator: (value: number) => {
      return value > 0 && value <= 3
    },
  },
})

const i18nUtils = useI18nUtils()

const { fetch } = useEntityFetch()

const { data: tree, status } = fetch(props.model)

const content = computed(
  () => {
    if (status.value !== FETCHING_STATUS.SUCCESS || !tree.value) {
      return []
    }

    let content = tree.value.content

    if (props.translate) {
      content = i18nUtils.translateResourceTree(content)
    }

    if (props.sort) {
      content = ArrayUtils.sortResourceTree(content)
    }

    return content
  }
)
</script>

<style scoped lang="scss">
/* No specific styles needed */
</style>
