<template>
  <TreeSelect
    :modelValue="selectedValue"
    @update:modelValue="setNewValue"
    filter
    filterMode="lenient"
    :options="autocomplete.categories"
    :disabled="disabled"
    :loading="isLoading"
    :placeholder="placeholder"
    class="md:w-80 w-full"
  />
</template>

<script setup>
import TreeSelect from "primevue/treeselect";
import {useAutocompleteStore} from "@/stores/autocomplete.js";
import {computed, onMounted, ref} from "vue";

const autocomplete = useAutocompleteStore();

const isLoading = ref(false);
const model = defineModel();

const props = defineProps({
  placeholder: {
    type: String,
    default: null,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});

const selectedValue = computed(() => {
  const id = model.value;
  return id ? {[String(id)]: true} : null;
});

function setNewValue(event) {
  model.value = Number(Object.keys(event)[0]);
}

onMounted(async () => {
  isLoading.value = true;
  await autocomplete.fetchCategories();
  isLoading.value = false;
});
</script>
