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

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

const { placeholder, label, type } = defineProps({
  placeholder: {
    type: String,
    default: () => useI18n().t("common.ui.misc.type"),
  },
  label: {
    type: String,
    default: () => useI18n().t("common.ui.misc.type"),
  },
  type: {
    type: String,
    default: null,
  },
});

const selectedUserType = defineModel({
  type: Object,
});
const userTypeOptions = ref([]);
const filteredOptions = ref([]);
const isLoading = ref(true);

const selectUserByValue = (value) => {
  selectedUserType.value = userTypeOptions.value.find(
    (option) => option.value === value,
  );
};

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,
    }));
    filteredOptions.value = userTypeOptions.value;

    if (type) {
      selectedUserType.value = userTypeOptions.value.find(
        (option) => option.value === type,
      );
    }
  } catch (error) {
    console.error("Failed to load user types:", error);
  } finally {
    isLoading.value = false;
  }
});

defineExpose({
  selectUserByValue,
});
</script>
