<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';
import { selectFilterOptionRefMod } from 'src/stores/utils';
import { QSelect } from 'quasar';

const model = defineModel<string | Date | null>();

const options = ref<Record<string, unknown>[]>([]);
let defaultFilter: (
  value: string,
  update: (callbackFn: () => void, afterFn?: (ref: QSelect) => void) => void,
) => void;

const props = withDefaults(
  defineProps<{
    id?: string;
    label?: string;
    option: Record<string, unknown>[];
    optionLabel?: string;
    optionValue?: string;

    readonly?: boolean;
    clearable?: boolean;
    incremental?: boolean;

    rules?: ((value: string) => string | true)[];
  }>(),
  { option: () => [], optionLabel: 'label', optionValue: 'value' },
);

defineEmits<{
  (e: 'filter', val: string, update: void): void;
}>();

onMounted(() => {
  defaultFilter = selectFilterOptionRefMod(
    ref(props.option),
    options,
    props.optionLabel,
  );
});

watch(
  () => props.option,
  () => {
    defaultFilter = selectFilterOptionRefMod(
      ref(props.option),
      options,
      props.optionLabel,
    );
  },
);
</script>
<template>
  <q-select
    outlined
    :clearable
    use-input
    emit-value
    map-options
    hide-selected
    hide-bottom-space
    :fill-input="!!model"
    :hide-dropdown-icon="readonly"
    input-debounce="0"
    :option-value="optionValue"
    :option-label="optionLabel"
    v-model="model"
    dense
    :readonly
    :label="label"
    :options="incremental ? option : options"
    :for="`select-${id}`"
    @filter="
      (val, update) => {
        incremental ? $emit('filter', val, update) : defaultFilter(val, update);
      }
    "
    :rules
  >
    <template v-slot:no-option>
      <q-item>
        <q-item-section class="text-grey">
          {{ $t('general.noData') }}
        </q-item-section>
      </q-item>
    </template>

    <template v-if="$slots.name" v-slot:selected-item="scope">
      <slot name="selected-item" :scope="scope"></slot>
    </template>

    <template v-if="$slots.option" v-slot:option="scope">
      <slot name="option" :scope="scope"></slot>
    </template>
  </q-select>
</template>
