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

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

import useStore, { User } from 'src/stores/user';
import { Lang } from 'src/utils/ui';

type SelectOption = User;

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

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

const { fetchList: getList, fetchById: 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,
        });
        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>
  <SelectInput
    v-model="value"
    incremental
    :label
    :placeholder
    :readonly
    :disable="disabled"
    :option="
      selectOptions.map((v) => {
        const ret = {
          label: (
            {
              [Lang.English]: [v.firstNameEN, v.lastNameEN].join(' '),
              [Lang.Thai]: [v.firstName, v.lastName].join(' '),
            } as const
          )[$i18n.locale],
          value: v.id,
        };
        return ret;
      })
    "
    :hide-selected="false"
    :fill-input="false"
    :rules="[(v: string) => !!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>
  </SelectInput>
</template>
