<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, watch } 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"),
  },
  accessScope: { type: String, default: null },
  unitId: { type: Number, default: null },
});

const { placeholder, label } = props;

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

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

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),
      );
    }
  });
};

const loadOptions = async () => {
  isLoading.value = true;
  try {
    const response = await userTypes(props.accessScope, props.unitId);
    userTypeOptions.value = Object.entries(response).map(([key, value]) => ({
      label: value,
      value: key,
    }));
    filteredOptions.value = userTypeOptions.value;
  } catch (error) {
    console.error("Failed to load user types:", error);
  } finally {
    isLoading.value = false;
  }
};

onMounted(loadOptions);

watch(() => [props.accessScope, props.unitId], loadOptions);
</script>
