<script setup lang="ts">


import {RecurrentOperation} from "@/models/recurrent-operation";
import {onMounted, ref} from "vue";
import {recurrentsService} from "@/services/recurrents-service";
import {useSpaceStore} from "@/stores/spaceStore";
import {useToast} from "primevue/usetoast";
import {Divider} from "primevue";
import {Category} from "@/models/category";
import {useRouter} from "vue-router";
import {useToolbarStore} from "@/stores/toolbar-store";

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


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

const fetchData = async () => {
  try {
    if (spaceStore.selectedSpaceId) {
      console.log('hereeee')
      let recurrentsResponse = await recurrentsService.fetchRecurrents(spaceStore.selectedSpaceId)
      recurrents.value =  recurrentsResponse
      console.log(recurrentsResponse)

    }
  } catch (e) {
    console.error(e)
    toast.add({
      severity: 'error',
      summary: 'Failed to fetch recurrents.',
      detail: error.message
    })
  }
}

onMounted(async () => {
  await fetchData()
  toolbar.registerHandler('openRecurrentCreation', () => {
    router.push('/recurrents/create')
  })
})


</script>

<template>
  <div class="card">
    <div v-for="key in recurrents.keys()" :key="recurrents[key].id"
         @click="router.push(`/recurrents/${recurrents[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-4xl">{{ recurrents[key].category.icon }}</span>
        <div class="flex-col items-start">
          <div class="flex-row"> {{ recurrents[key].name }}</div>
          <div class="flex flex-row text-sm">{{ recurrents[key].category.name }}</div>
        </div>

        </div>
        <div class="items-center flex-col">
        <span class="text-lg !font-semibold">{{recurrents[key].amount}}₽ </span>
        <span class="text-sm">каждое {{ recurrents[key].date }} число </span>
        </div>
        <i class="pi pi-angle-right !font-extralight"/>
      </div>
      <Divider v-if="key+1 !== recurrents.length" class="!m-0 !py-3"/>
    </div>

  </div>
</template>

<style scoped>

</style>