<!--
Liste déroulante dédiée à l'affichage d'objets Enum

@see https://vuetifyjs.com/en/components/selects/
-->

<template>
  <main>
    <v-skeleton-loader
      v-if="$fetchState.pending"
      type="list-item"
      loading
    />

    <v-select
      v-else
      :label="$t(fieldLabel)"
      :value="data"
      :items="items"
      item-text="label"
      item-value="value"
      :rules="rules"
      :disabled="readonly"
      :error="error || !!violation"
      :error-messages="errorMessage || violation ? $t(violation) : ''"
      @change="onChange($event)"
    />
  </main>
</template>

<script setup lang="ts">
import {useNuxtApp} from "#app";
import {useFieldViolation} from "~/composables/form/useFieldViolation";
import {ref, Ref} from "@vue/reactivity";
import {useEnumFetch} from "~/composables/data/useEnumFetch";
import {Enum} from "~/types/data";

const props = defineProps({
  enumType: {
    type: String,
    required: true
  },
  label: {
    type: String,
    required: false,
    default: null
  },
  field: {
    type: String,
    required: false,
    default: null
  },
  data: {
    type: String,
    required: false,
    default: null
  },
  readonly: {
    type: Boolean,
    required: false
  },
  rules: {
    type: Array,
    required: false,
    default: () => []
  },
  error: {
    type: Boolean,
    required: false
  },
  errorMessage: {
    type: String,
    required: false,
    default: null
  }
})

const { emit } = useNuxtApp()

const fieldLabel = props.label ?? props.field

const { enumType } = props

const { violation, onChange } = useFieldViolation(props.field, emit)

const items: Ref<Enum> = ref([])

const { fetch } = useEnumFetch()
const { data: fetched, pending } = fetch(enumType)

items.value = fetched.value || []

</script>

<style scoped>
</style>
