<template>
  <w-select
    v-bind="$props"
    use-input
    :fill-input="!multiple"
    :hide-selected="!multiple"
    :options="filteredOptions"
    @filter="filterFn"
    @update:model-value="onInput"
  >
    <template #no-option>
      <q-item>
        <q-item-section class="text-grey">
          No results
        </q-item-section>
      </q-item>
    </template>
    <template v-for="(_, slot) of $slots" #[slot]="scope">
      <slot :name="slot" v-bind="{...scope}" />
    </template>
  </w-select>
</template>
<script>
import WSelect from "../select/WSelect";

export default {
  name: "WSelectFilter",
  mixins: [WSelect],
  inheritAttrs: true,
  props: {
    multiple: {
      type: Boolean,
      default: false,
    },
  },
  emits: ["update:modelValue"],
  data() {
    return {
      filterQuery: "",
    };
  },
  computed: {
    filteredOptions() {
      return this.options.filter(v => v[this.optionLabel || "label"].toLowerCase().indexOf(this.filterQuery) > -1);
    },
  },
  methods: {
    filterFn (val, update, abort) {
      update(
        () => { this.filterQuery = val.toLowerCase(); },
        ref => {
          if (val !== "" && ref.options.length && ref.optionIndex === -1) {
            ref.moveOptionSelection(1, true); // focus the first selectable option and do not update the input-value
            ref.toggleOption(ref.options[ref.optionIndex], true); // toggle the focused option
          }
        }
      );
    },
    onInput(option) {
      this.$emit("update:modelValue", option);
    },
  },
};
</script>
