<script setup>
import { useDebounceFn } from '@vueuse/core'
import {ref, defineModel} from 'vue'
import { NSelect } from 'naive-ui'

const value = defineModel('value')
const objectId = defineModel('objectid')
const options = ref()
const loading = ref(false)

const debounceSearch = useDebounceFn((query) => {
    axios.post('/api/fias', {
        search: query
    }).then((res) => {
        options.value = res.data
        loading.value = false
    })
}, 1000, { maxWait: 5000 })

const handleSearch = async (query) => {
    if (!query.length) {
        options.value = []
        return
    }

    loading.value = true

    await debounceSearch(query)
}

const updateValue = (selectedValue) => {
    const oId = options.value.find((itm) => itm.full_name === selectedValue)
    objectId.value = oId.objectid
}
</script>

<template>
    <NSelect v-model:value="value" @update-value="(v) => updateValue(v)" filterable placeholder="" :options="options"
        label-field="full_name" value-field="full_name" :loading="loading" clearable remote
        :clear-filter-after-select="false" @search="handleSearch" />
</template>