<template>
  <DefaultSelect
    v-model="selected"
    v-bind="$attrs"
    use-input
    hide-selected
    fill-input
    clearable
    :options="filteredOptions"
    :label
    :loading
    :placeholder
    @filter="filterFn"
  >
    <template #no-option>
      <q-item>
        <q-item-section class="text-grey">
          {{ $t("http.errors.no_records_found") }}
        </q-item-section>
      </q-item>
    </template>
  </DefaultSelect>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { getPositions } from "src/api/position";
import { normalizeString } from "src/helpers/utils";
import { useI18n } from "vue-i18n";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";

const { label, placeholder } = defineProps({
  label: {
    type: String,
    default: () => useI18n().t("associado.position"),
  },
  placeholder: {
    type: String,
    default: () => useI18n().t("common.actions.search"),
  },
});

const selected = defineModel({ type: Object });

const loading = ref(true);
const baseOptions = ref([]);
const filteredOptions = ref([]);

const filterFn = (val, update) => {
  const needle = normalizeString(val);
  filteredOptions.value = baseOptions.value.filter((v) =>
    normalizeString(v.label).includes(needle),
  );
  update();
};

onMounted(async () => {
  try {
    const items = await getPositions();
    baseOptions.value = items.map((p) => ({ label: p.name, value: p.id }));
    filteredOptions.value = baseOptions.value;
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
});
</script>
