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

<script setup>
import { ref, watchEffect, defineEmits, onUnmounted } from 'vue'
import { searchPropsDesc } from './state'
import UISelect from './select.vue'

const props = defineProps(searchPropsDesc)
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>