<script setup>
    import { ref } from 'vue';
    import VueMultiselect from 'vue-multiselect'
    import { searchcities } from '../../services/public';
    import { useI18n } from 'vue-i18n';

    const options = ref([]);
    const isLoading = ref(false);
    const { t } = useI18n();
    
    defineProps({
        selectedCities: {
            type: Array
        },
        multiple: {
            type: Boolean,
            default: false
        },
        disabled: {
            type: Boolean,
            default: false
        },
        required: {
            type: Boolean,
            default: false
        }
    });
    defineEmits(['update:selectedCities', 'clear-option'])

    const searchState = async(query) => {
        isLoading.value = true;
        const resp = await searchcities(query);
        options.value = resp;
        isLoading.value = false;
    }
</script>

<template>
    <VueMultiselect
        :value="selectedCities"
        @input="$event => $emit('update:selectedCities', $event.target.value)"
        :options="options"
        :multiple="multiple"
        :searchable="true"
        :loading="isLoading"
        :close-on-select="true"
        :disabled="disabled"
        @search-change="searchState"
        @remove="$emit('clear-option')"
        label="city_name"
        track-by="city_name"
        :placeholder="t('labels.selectCity')"
        :selectLabel="t('global.helpSelected')"
        :selectedLabel="t('global.selected')"
        :deselectLabel="t('global.removeSelected')"
        :class="[
            required ? 'border-required' : '',
        ]"
    >
        <template #noResult>
            {{ t('global.notFound') }}
        </template>
        <template #noOptions>
            {{ t('global.emptyList') }}
        </template>
    </VueMultiselect>
</template>

<style src="vue-multiselect/dist/vue-multiselect.css"></style>

<style scoped>

</style>