<template>
  <DefaultSelect
    v-model="selected"
    v-bind="$attrs"
    use-input
    hide-selected
    fill-input
    clearable
    :options="options"
    :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 { getAssociados } from "src/api/user";
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.associado"),
  },
  placeholder: {
    type: String,
    default: () => useI18n().t("common.actions.search"),
  },
});

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

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

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

onMounted(async () => {
  try {
    const associados = await getAssociados();
    baseOptions.value = associados.map((a) => ({
      label: a.name,
      value: a.id,
      data: a,
    }));
    options.value = baseOptions.value;
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
});
</script>
