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

const model = defineModel<string | Record<string, unknown> | 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;
    placeholder?: string;

    hideSelected?: boolean;
    readonly?: boolean;
    clearable?: boolean;
    incremental?: boolean;
    fillInput?: boolean;
    disable?: boolean;

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

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
    :placeholder="placeholder"
    outlined
    :clearable
    :disable
    use-input
    emit-value
    map-options
    :hideSelected
    hide-bottom-space
    :fill-input="fillInput && !!model"
    :hide-dropdown-icon="readonly"
    input-debounce="0"
    :option-value="optionValue"
    :option-label="optionLabel"
    v-model="model"
    dense
    autocomplete="off"
    :readonly
    :label="label"
    :options="incremental ? option : options"
    :for="`${id}`"
    @filter="
      (val, update) => {
        incremental ? $emit('filter', val, update) : defaultFilter(val, update);
      }
    "
    :rules
  >
    <template v-if="$slots.prepend" v-slot:prepend>
      <slot name="prepend"></slot>
    </template>

    <template v-slot:no-option>
      <slot name="noOption"></slot>

      <q-item v-if="!$slots.noOption">
        <q-item-section class="text-grey">
          {{ $t('general.noData') }}
        </q-item-section>
      </q-item>
    </template>

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

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