<script setup lang="ts">
import { ref, onMounted } from 'vue';

import { createSelect, SelectProps } from './select';
import SelectBase from './SelectBase.vue';

import { ProductGroup } from 'stores/product-service/types';

import useStore from 'stores/product-service';

type SelectOption = ProductGroup;

const value = defineModel<string | null | undefined>('value', {
  required: true,
});
const valueOption = defineModel<SelectOption>('valueOption', {
  required: false,
});

const selectOptions = ref<SelectOption[]>([]);

const { fetchProductGroup: getList, fetchProductGroupById: getById } =
  useStore();

defineEmits<{
  (e: 'create'): void;
}>();

type ExclusiveProps = {
  selectFirstValue?: boolean;
};

const props = defineProps<SelectProps<typeof getList> & ExclusiveProps>();

const { getOptions, setFirstValue, getSelectedOption, filter } =
  createSelect<SelectOption>(
    {
      value,
      valueOption,
      selectOptions,
      getList: async (query) => {
        const ret = await getList({
          query,
          ...props.params,
          activeOnly: true,
        });
        if (ret) return ret.result;
      },
      getByValue: async (id) => {
        const ret = await getById(id);
        if (ret) return ret;
      },
    },
    { valueField: 'id' },
  );

onMounted(async () => {
  await getOptions();

  if (props.autoSelectOnSingle && selectOptions.value.length === 1) {
    setFirstValue();
  }

  if (props.selectFirstValue) {
    setDefaultValue();
  } else await getSelectedOption();
});

function setDefaultValue() {
  setFirstValue();
}
</script>
<template>
  <SelectBase
    v-model="value"
    incremental
    option-label="code"
    option-value="id"
    :label
    :placeholder
    :readonly
    :disable="disabled"
    :options="selectOptions"
    :hide-selected="false"
    :fill-input="false"
    :rules="[
      (v: string) => !props.required || !!v || $t('form.error.required'),
    ]"
    @filter="filter"
  >
    <template #append v-if="clearable">
      <q-icon
        v-if="!readonly && value"
        name="mdi-close-circle"
        @click.stop="value = ''"
        class="cursor-pointer clear-btn"
      />
    </template>

    <template #option="{ scope }">
      <q-item
        v-if="scope.opt"
        v-bind="scope.itemProps"
        class="row items-center"
      >
        <q-item-section>
          {{ scope.opt.name }}
          <span class="app-text-muted text-caption">
            {{ scope.opt.code }}
          </span>
        </q-item-section>
      </q-item>
    </template>

    <template #selected-item="{ opt }">
      <q-item-section v-if="opt">
        {{ opt.name }}
        <span class="app-text-muted text-caption">
          {{ opt.code }}
        </span>
      </q-item-section>
    </template>
  </SelectBase>
</template>
