<template>
  <DefaultSelect
    v-model="selectedCategory"
    v-bind="$attrs"
    use-input
    hide-selected
    fill-input
    clearable
    :options="categoryOptions"
    :label
    :loading
    :placeholder
    class="input-violet"
    @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 { getCategories } from "src/api/category";
import { normalizeString } from "src/helpers/utils";
import { useI18n } from "vue-i18n";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";

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

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

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

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

onMounted(async () => {
  try {
    const categories = await getCategories(type);
    baseOptions.value = categories.map((c) => ({
      label: c.name,
      value: c.id,
    }));
    categoryOptions.value = baseOptions.value;
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
});
</script>
