<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 {categoriesService} from "@/services/categories-service";
import {useToolbarStore} from "@/stores/toolbar-store";
import {useRouter} from "vue-router";

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



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

const fetchData = async () => {
  try {
    if (spaceStore.selectedSpaceId !== null) {
      let spaceId = spaceStore.selectedSpaceId!!
      categories.value = await categoriesService.fetchCategories(spaceId)
    }
  } 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('createCategory', () => {
    console.log("create cateogiry")
    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-col items-start">
          <div class="flex-row"> {{ categories[key].icon }} {{ categories[key].name }}</div>
          <div class="flex flex-row text-sm">{{ categories[key].description }}</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>