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

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

import useStore, { Customer, CustomerBranch } from 'src/stores/customer';

type SelectOption = CustomerBranch & { customer: Customer };

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

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

const {
  fetchListCustomerBranch: getList,
  fetchListCustomerBranchById: getById,
} = useStore();

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

type ExclusiveProps = {
  simple?: boolean;
  simpleBranchNo?: 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,
          includeCustomer: 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();
  }

  await getSelectedOption();
});
</script>
<template>
  <SelectInput
    v-model="value"
    option-value="id"
    incremental
    :label
    :placeholder
    :readonly
    :disable="disabled"
    :option="selectOptions"
    :hide-selected="false"
    :fill-input="false"
    :rules="[(v: string) => !!v || $t('form.error.required')]"
    @filter="filter"
  >
    <template #selected-item="{ opt }">
      <SelectCustomerItem
        v-if="typeof opt === 'object'"
        :data="opt"
        :simple
        :simple-branch-no
        single-line
      />
    </template>

    <template #before-options v-if="creatable">
      <q-item
        :disable="creatableDisabled"
        clickable
        v-close-popup
        @click.stop="$emit('create')"
      >
        <q-item-section>
          <span class="row items-center">
            <q-icon
              name="mdi-plus-circle-outline"
              class="q-mr-sm"
              style="color: hsl(var(--positive-bg))"
            />
            <b>
              {{ $t('general.add', { text: $t('quotation.newCustomer') }) }}
            </b>
            <span
              v-if="creatableDisabled && creatableDisabledText"
              class="app-text-muted q-pl-xs"
              style="font-size: 80%"
            >
              {{ creatableDisabledText }}
            </span>
          </span>
        </q-item-section>
      </q-item>

      <q-separator class="q-mx-sm" />
    </template>

    <template #option="{ opt, scope }">
      <q-item v-bind="scope.itemProps">
        <SelectCustomerItem :data="opt" :simple :simple-branch-no />
      </q-item>

      <q-separator class="q-mx-sm" />
    </template>

    <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>
