<script setup lang="ts">
import { getSelectedProfile } from '@/api/profile'
import { TransactionApiClient, type TransactionCategoryTree } from '@/api/transaction'
import { computed, onMounted, ref, watch, type Ref } from 'vue'
import { useRoute } from 'vue-router'
import VueSelect, { type Option } from 'vue3-select-component'

const route = useRoute()
const model = defineModel<number | null>({ required: true })
defineProps<{ required?: boolean }>()
defineEmits<{ categorySelected: [TransactionCategoryTree | null] }>()
const categories: Ref<TransactionCategoryTree[]> = ref([])
const selectedCategory: Ref<TransactionCategoryTree | null> = ref(null)
const options: Ref<Option<TransactionCategoryTree>[]> = computed(() => {
  return categories.value.map((c) => {
    return { label: c.name, value: c }
  })
})

watch(model, (newValue) => {
  selectedCategory.value = newValue === null ? null : getCategoryById(newValue)
})

onMounted(async () => {
  const api = new TransactionApiClient(getSelectedProfile(route))
  categories.value = await api.getCategoriesFlattened()
  if (model.value !== null) {
    selectedCategory.value = getCategoryById(model.value)
  }
})

function getCategoryById(id: number): TransactionCategoryTree | null {
  for (const c of categories.value) {
    if (c.id === id) return c
  }
  return null
}
</script>
<template>
  <VueSelect
    class="category-select"
    v-model="selectedCategory"
    :options="options"
    placeholder="Select a category"
    @option-selected="model = selectedCategory?.id ?? null"
    @option-deselected="model = null"
  >
    <template #option="{ option }">
      {{ '&nbsp;'.repeat(option.value.depth * 4) }} {{ option.label }}
    </template>
  </VueSelect>
</template>
