<template>
  <DefaultSelect
    v-model="selectedOption"
    v-bind="$attrs"
    use-input
    hide-selected
    fill-input
    clearable
    :options="filteredOptions"
    :loading="isLoading"
    :placeholder
    :label
    @filter="filterFn"
  />
</template>

<script setup>
import { onMounted, ref, computed } from "vue";
import { userTypes } from "src/api/user";
import { useI18n } from "vue-i18n";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";

const props = defineProps({
  placeholder: {
    type: String,
    default: () => useI18n().t("common.ui.misc.type"),
  },
  label: {
    type: String,
    default: () => useI18n().t("common.ui.misc.type"),
  },
  excludeTypes: {
    type: Array,
    default: () => [],
  },
});

const { placeholder, label } = props;

const userTypeOptions = ref([]);
const filteredOptions = ref([]);
const isLoading = ref(true);

const modelValue = defineModel({ type: String, default: null });

const selectedOption = computed({
  get() {
    return (
      userTypeOptions.value.find((opt) => opt.value === modelValue.value) ??
      null
    );
  },
  set(option) {
    modelValue.value = option?.value ?? null;
  },
});

const filterFn = (val, update) => {
  update(() => {
    if (val === "") {
      filteredOptions.value = userTypeOptions.value;
    } else {
      const needle = val.toLowerCase();
      filteredOptions.value = userTypeOptions.value.filter((v) =>
        v.label.toLowerCase().includes(needle),
      );
    }
  });
};

onMounted(async () => {
  try {
    const response = await userTypes();
    userTypeOptions.value = Object.entries(response)
      .map(([key, value]) => ({ label: value, value: key }))
      .filter((opt) => !props.excludeTypes.includes(opt.value));
    filteredOptions.value = userTypeOptions.value;
  } catch (error) {
    console.error("Failed to load user types:", error);
  } finally {
    isLoading.value = false;
  }
});
</script>
