<template>
  <UiInputAutocomplete
    :model-value="modelValue"
    :field="field"
    :items="items"
    :is-loading="status===FETCHING_STATUS.PENDING"
    :return-object="false"
    item-title="label"
    item-value="value"
    :variant="variant"
    @update:model-value="$emit('update:model-value', $event)"
  />
</template>

<script setup lang="ts">
import type { ComputedRef, PropType } from 'vue'
import { useEnumFetch } from '~/composables/data/useEnumFetch'
import ArrayUtils from '~/services/utils/arrayUtils'
import type { Enum } from '~/types/data'
import {FETCHING_STATUS} from "~/types/enum/data";

const emit = defineEmits(['update:model-value'])

const props = defineProps({
  modelValue: {
    type: String as PropType<string | null>,
    required: false,
    default: null,
  },
  enumName: {
    type: String,
    required: true,
  },
  field: {
    type: String,
    required: false,
    default: null,
  },
  label: {
    type: String,
    required: false,
    default: null,
  },
  /**
   * @see https://vuetifyjs.com/en/api/v-autocomplete/#props-variant
   */
  variant: {
    type: String as PropType<
      | 'filled'
      | 'outlined'
      | 'plain'
      | 'underlined'
      | 'solo'
      | 'solo-inverted'
      | 'solo-filled'
      | undefined
    >,
    required: false,
    default: 'outlined',
  },
})

const { fetch } = useEnumFetch()

const { data: enumItems, status } = fetch(props.enumName)

const items: ComputedRef<Array<Enum>> = computed(() => {
  if (!enumItems.value) {
    return []
  }
  return ArrayUtils.sortObjectsByProp(enumItems.value, 'label') as Array<Enum>
})

// Nettoyer les données lors du démontage du composant
onBeforeUnmount(() => {
  // Nettoyer les références du store si nécessaire
  if (process.client) {
    clearNuxtData(props.enumName)
    // Forcer le garbage collection des objets Parameters
    enumItems.value = null
  }
})
</script>

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