<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, logo_url: string }[]
    errorMessages?: string[] | string
}>()


const model = defineModel<{ value: number, title: string, logo_url: 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"
                :alt="`${model.title}`"
                :src="`${model.logo_url}`"
            />
        </template>
        <template #item="{ item, props: itemProps }">
            <v-list-item v-bind="itemProps">
                <template #prepend>
                    <img style="padding:0.25em" width="40" height="40" :src="`${item.logo_url}`"  alt=""/>
                </template>

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