<template>
  <q-select
    v-bind="$attrs"
    v-model="selectedUserType"
    use-input
    hide-selected
    fill-input
    :options="filteredOptions"
    :clearable
    :loading
    :readonly
    :label
    :rules
    :error
    :error-message
    @filter="filterFn"
  />
</template>
<script setup>
import { onMounted, ref } from "vue";
import { userTypes } from "src/api/user";
import { useI18n } from "vue-i18n";

const { label, rules, type } = defineProps({
  label: {
    type: String,
    default: () => useI18n().t("common.ui.misc.type"),
  },
  rules: {
    type: Array,
    default: () => [],
  },
  type: {
    type: String,
    default: null,
  },
  clearable: {
    type: Boolean,
    default: true,
  },
  readonly: {
    type: Boolean,
    default: false,
  },
  error: {
    type: Boolean,
    default: false,
  },
  errorMessage: {
    type: String,
    default: "",
  },
});

const selectedUserType = defineModel();
const userTypeOptions = ref([]);
const filteredOptions = ref([]);
const isLoading = ref(false);
const searchQuery = ref("");

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

const filterFn = (val, update) => {
  searchQuery.value = val;
  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 {
    isLoading.value = true;
    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>
