<template>
  <UiInputTreeSelect
    :model-value="modelValue"
    :items="hierarchicalItems"
    v-bind="$attrs"
    :loading="pending"
    @update:model-value="$emit('update:modelValue', $event)"
  />
</template>

<script setup lang="ts">
import { useEntityFetch } from '~/composables/data/useEntityFetch'
import EventCategory from '~/models/Core/EventCategory'

const props = defineProps({
  modelValue: {
    type: Array as PropType<string[]>,
    required: true
  }
})

const i18n = useI18n()

const { fetchCollection } = useEntityFetch()

const { data: categories, pending } = fetchCollection(EventCategory)

// Transform event categories into hierarchical items for TreeSelect
const hierarchicalItems = computed(() => {
  if (!categories.value || categories.value.length === 0) {
    return []
  }

  const result = []
  const familiesMap = new Map()
  const subFamiliesMap = new Map()

  // First pass: collect all unique families and subfamilies
  categories.value.items.forEach(category => {
    if (!category.famillyLabel || !category.subfamillyLabel || !category.genderLabel) return

    // Create unique keys for families and subfamilies
    const familyKey = category.famillyLabel
    const subfamilyKey = `${category.famillyLabel}-${category.subfamillyLabel}`

    // Add family if not already added
    if (!familiesMap.has(familyKey)) {
      familiesMap.set(familyKey, {
        id: `family-${familyKey}`,
        label: i18n.t(category.famillyLabel),
        type: 'category',
        level: 0
      })
    }

    // Add subfamily if not already added
    if (!subFamiliesMap.has(subfamilyKey)) {
      subFamiliesMap.set(subfamilyKey, {
        id: `subfamily-${subfamilyKey}`,
        label: i18n.t(category.subfamillyLabel),
        type: 'subcategory',
        parentId: `family-${familyKey}`,
        level: 1
      })
    }
  })

  // Convert families map to array and sort alphabetically by label
  const sortedFamilies = Array.from(familiesMap.values()).sort((a, b) =>
    a.label.localeCompare(b.label)
  )

  // Add sorted families to result
  sortedFamilies.forEach(family => {
    result.push(family)
  })

  // Convert subfamilies map to array and sort alphabetically by label
  const sortedSubfamilies = Array.from(subFamiliesMap.values()).sort((a, b) =>
    a.label.localeCompare(b.label)
  )

  // Add sorted subfamilies to result
  sortedSubfamilies.forEach(subfamily => {
    result.push(subfamily)
  })

  // Collect all genders first, then sort and add to result
  const genders = []
  categories.value.items.forEach(category => {
    if (!category.famillyLabel || !category.subfamillyLabel || !category.genderLabel) return

    const familyKey = category.famillyLabel
    const subfamilyKey = `${category.famillyLabel}-${category.subfamillyLabel}`

    genders.push({
      id: `gender-${category.id}`,
      label: i18n.t(category.genderLabel),
      value: category.id.toString(),
      type: 'item',
      parentId: `subfamily-${subfamilyKey}`,
      level: 2
    })
  })

  // Sort genders alphabetically by label and add to result
  genders.sort((a, b) => a.label.localeCompare(b.label)).forEach(gender => {
    result.push(gender)
  })

  return result
})
</script>

<style scoped lang="scss">
/* No specific styles needed */
</style>
