<template>
  <UiInputAutocomplete
    :model-value="modelValue"
    :field="field"
    :items="items"
    :is-loading="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 { useEnumFetch } from '~/composables/data/useEnumFetch'
import ArrayUtils from '~/services/utils/arrayUtils'
import type { ComputedRef } from '@vue/reactivity'
import type { Enum } from '~/types/data'
import type { PropType } from '@vue/runtime-core'

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: 'filled',
  },
})

const { fetch } = useEnumFetch()

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

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

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