<script setup lang="ts">
import { ref, nextTick } from 'vue'
import axios from 'axios'

const props = defineProps<{
    prefilledOptions: { value: number, title: string }[]
    errorMessages?: string[] | string
}>()

const model = defineModel<{ value: number, title: string } | null>()

const aircraftOptions = ref(props.prefilledOptions ?? [])
const autocompleteRef = ref<any>(null)

const onFocus = () => {
    nextTick(() => {
        const input = autocompleteRef.value?.$el?.querySelector('input')
        input?.select()
    })
}

const searchAircraft = async (query: string) => {
    if (!query || query.length < 2) {
        aircraftOptions.value = props.prefilledOptions ?? []
        return
    }

    if (query === model.value?.title) return

    const { data } = await axios.get('/search/aircraft', { params: { q: query } })
    aircraftOptions.value = data
}
</script>

<template>
    <v-autocomplete
        ref="autocompleteRef"
        v-model="model"
        label="Aircraft"
        :items="aircraftOptions"
        :error-messages="errorMessages"
        item-title="title"
        @update:search="searchAircraft"
        :custom-filter="() => true"
        @focus="onFocus"
        hint="Showing closest matches to the imported value"
        placeholder="B738"
        clearable
        hide-no-data
        return-object
    />
</template>
