<script setup lang="ts">

import {useSpaceStore} from "@/stores/spaceStore";
import {useToast} from "primevue/usetoast";
import {Divider} from "primevue";
import {onMounted, ref} from "vue";
import {Category} from "@/models/category";
import {useToolbarStore} from "@/stores/toolbar-store";
import {useRouter} from "vue-router";
import {useCategoriesStore} from "@/stores/categories-store";

const toast = useToast()
const spaceStore = useSpaceStore()
const categoryStore = useCategoriesStore()
const toolbar = useToolbarStore()
const router = useRouter()


const categories = ref<Category[]>([])

const fetchData = async () => {
  try {
    if (spaceStore.selectedSpaceId !== null) {
      let spaceId = spaceStore.selectedSpaceId!!
      await categoryStore.fetchCategories(spaceId)
      categories.value = categoryStore.categories
    }
  } catch (error: Error) {
    toast.add({
      severity: 'error',
      summary: 'Failed to fetch categories.',
      detail: error.message
    })
  }
}

const toCreation = () => {
  router.push(`/categories/create`)
}

onMounted(async () => {
  await fetchData()
  toolbar.registerHandler('openCategoryCreation', () => {
    toCreation()
  })
})


</script>

<template>


  <div class="card">
    <div v-for="key in categories.keys()" :key="categories[key].id"
         @click="router.push(`/categories/${categories[key].id}/edit`)"
         class="flex flex-col  w-full gap-0 pl-5  items-start justify-items-center font-bold ">
      <div class="flex-row  w-full items-center justify-between">
        <div class="flex-row items-center gap-2 ">
          <span class="text-3xl"> {{ categories[key].icon }}</span>
          <div class="flex-col !font-bold "> {{ categories[key].name }}
            <div class="flex flex-row text-sm">{{ categories[key].description }}</div>
          </div>
        </div>
        <i class="pi pi-angle-right !font-extralight"/>
      </div>
      <Divider v-if="key+1 !== categories.length" class="!m-0 !py-3"/>
    </div>
  </div>
</template>

<style scoped>

</style>