<template>
    <UISelect ref="selectVM" class-name="search" v-bind="props" :readonly="false" :label-value="labelValue" :options="options" @update:model-value="update">
        <template v-for="(slot, name) in $slots" #[name]="raw">
            <slot :name="name" v-bind="raw" />
        </template>
        <template #icon>
            <ui-icon v-if="labelValue" type="close" class="clear" small @click="clearHandler" />
        </template>
        <template #preIcon>
            <ui-icon type="search" color="rgba(255,255,255,.3)" small />
        </template>
    </UISelect>
</template>

<script setup lang="ts">
import { defineEmits, onUnmounted, ref, watchEffect } from 'vue'
import UISelect from '../select/select.vue'
import { searchProps } from './search'

const props = defineProps(searchProps)
const labelValue = ref('')
const options = ref([])
const selectVM = ref()
const emit = defineEmits(['update:modelValue'])

watchEffect(() => {
    options.value = labelValue.value ? props.options.filter(({ label }) => label.includes(labelValue.value)) : props.options
})

const clearHandler = () => {
    emit('update:modelValue', null)
    update('')
    inputEl.focus()
}

const update = val => {
    const valItem = props.options.find(({ value }) => value === val)
    const labelItem = props.options.find(({ label }) => label === val)
    const item = valItem || labelItem

    if (item) {
        labelValue.value = item.label
        emit('update:modelValue', item.value)
    } else if (typeof val === 'string') {
        labelValue.value = val
    }
}

update(props.modelValue)
const blurHandler = () => {
    setTimeout(() => update(props.modelValue), 100)
}

let inputEl
watchEffect(() => {
    if (selectVM.value) {
        if (inputEl) {
            inputEl.removeEventListener('blur', blurHandler)
            inputEl = null
        }
        inputEl = selectVM.value.vmRef.input
        inputEl.addEventListener('blur', blurHandler)
    }
})

onUnmounted(() => {
    inputEl && inputEl.removeEventListener('blur', blurHandler)
})
</script>
