<script setup lang="ts">
import { ref, nextTick } from 'vue'
import axios from 'axios'
import {usePage} from "@inertiajs/vue3";
import type {SharedProps} from "@/Types/types";

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

const page = usePage<SharedProps>().props

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

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

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

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

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

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

<template>
    <v-autocomplete
        ref="autocompleteRef"
        v-model="model"
        label="Airline"
        :items="airlineOptions"
        :error-messages="errorMessages"
        item-title="title"
        @update:search="searchAirlines"
        @focus="onFocus"
        hint=""
        placeholder="SriLankan Airlines"
        clearable
        hide-no-data
        return-object
    >
        <template #prepend-inner>
            <img
                v-if="model"
                style="padding: 0.25em"
                width="40"
                height="40"
                :src="`${page.logo_api_url}/airlines/logos/tail/id/${model.value}`"
            />
        </template>
        <template #item="{ item, props: itemProps }">
            <v-list-item v-bind="itemProps">
                <template #prepend>
                    <img style="padding:0.25em" width="40" height="40" :src="`${page.logo_api_url}/airlines/logos/tail/id/${item.value}`"  alt=""/>
                </template>

            </v-list-item>
        </template>
    </v-autocomplete>
</template>
