<template>
  <DefaultSelect
    v-model="selectedPartner"
    v-bind="$attrs"
    use-input
    hide-selected
    fill-input
    clearable
    :options="partnerOptions"
    :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 { getPartnerAgreements, getConvenios } from "src/api/partnerAgreement";
import { normalizeString } from "src/helpers/utils";
import { useI18n } from "vue-i18n";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";

const { label, placeholder, forAssociado } = defineProps({
  label: {
    type: String,
    default: () => useI18n().t("ui.navigation.convenios"),
  },
  placeholder: {
    type: String,
    default: () => useI18n().t("common.actions.search"),
  },
  forAssociado: {
    type: Boolean,
    default: false,
  },
});

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

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

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

onMounted(async () => {
  try {
    const partners = await (forAssociado ? getConvenios() : getPartnerAgreements());
    baseOptions.value = partners.map((p) => ({
      label: p.trade_name || p.company_name,
      value: p.id,
    }));
    partnerOptions.value = baseOptions.value;
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
});
</script>
