<template>
  <SearchSelect
    :model-value="modelValue"
    :options="options"
    :placeholder="placeholder"
    option-value="name"
    option-label="name"
    creatable
    :size="size"
    @update:model-value="onUpdate"
    @focus="ensureLoaded"
  />
</template>

<script setup lang="ts">
import { computed } from 'vue'
import SearchSelect from './SearchSelect.vue'

const props = withDefaults(defineProps<{
  modelValue: string
  placeholder?: string
  size?: 'xs' | 'sm' | 'md' | 'lg'
}>(), {
  placeholder: 'Nom du champ',
  size: 'xs',
})

const emit = defineEmits<{
  'update:modelValue': [value: string]
}>()

const { suggestions, load } = useCustomFieldNameSuggestions()

const options = computed(() => (suggestions.value ?? []).map(name => ({ name })))

function ensureLoaded(): void {
  void load()
}

function onUpdate(value: string | number): void {
  emit('update:modelValue', String(value ?? ''))
}
</script>
