<script setup>
import collect from "collect.js";
import { computed, onMounted, useAttrs, ref } from "vue";
const props = defineProps({
  options: {
    type: Array,
    required: true
  },
  emitValue: {
    type: Boolean,
    default: true
  },
  mapOptions: {
    type: Boolean,
    default: true
  }
});
const userString = ref("");
const items = computed(() => {
  const filteredItems = collect(props.options).filter((item) => {
    if (userString.value === "") {
      return true;
    }
    return item.label.toLowerCase().includes(userString.value);
  }).toArray();
  const groups = collect(filteredItems).unique("group").pluck("group").sort();
  const options = collect();
  groups.each((group) => {
    const items2 = collect(filteredItems).where("group", group).toArray();
    options.push({ label: group, is_group: true, disable: true }).push(...items2);
  });
  return options.toArray();
});
const model = defineModel();
const attrs = useAttrs();
const handleItemUniqueByGroup = (items2) => {
  return;
  if (!attrs.hasOwnProperty("multiple") || attrs.multiple === false) {
    return;
  }
};
onMounted(() => {
});
const filterFn = (val, update, abort) => {
  if (val === "") {
    update(() => {
      userString.value = "";
    });
    return;
  }
  const needle = val.toLowerCase();
  update(() => {
    userString.value = needle;
  });
};
</script>

<template>
    <q-select v-model="model" v-bind="$light.getInputProps($props)" :options="items"
        @update:model-value="handleItemUniqueByGroup" input-debounce="0" @filter="filterFn" :style="$light.styles.input"
        :emit-value="emitValue" :map-options="mapOptions">
        <template v-slot:option="scope">
            <q-item v-if="scope.opt.is_group" v-bind="{ ...scope.itemProps }" class="text-xs bg-grey-4"
                :key="scope.opt.label">
                <q-item-section class="!cursor-default">
                    {{ scope.opt.label || "Ungroup" }}
                </q-item-section>
            </q-item>
            <q-item v-else v-bind="{ ...scope.itemProps }" :key="scope.opt.value">
                <q-item-section class="q-pl-md">{{ scope.opt.label }}</q-item-section>
            </q-item>
        </template>
        <template v-slot:no-option>
            <q-item>
                <q-item-section class="text-grey">
                    No results
                </q-item-section>
            </q-item>
        </template>
    </q-select>
</template>
