<script setup lang="ts">


import {RecurrentOperation} from "@/models/recurrent-operation";
import {onMounted, ref} from "vue";
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";
import {useRecurrentsStore} from "@/stores/recurrent-store";

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


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

const fetchData = async () => {
  try {
    if (spaceStore.selectedSpaceId) {
      await recurrentsStore.fetchRecurrents(spaceStore.selectedSpaceId)
      recurrents.value = recurrentsStore.recurrents

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

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


</script>

<template>
  <div class="flex !pb-10">
  <div class="flex card">
    <span v-if="recurrents.length==0">Looks like that you haven't create any recurrent yet. <router-link to="/recurrents/create" class="!text-blue-400">Try to create some first.</router-link></span>
    <div v-else v-for="key in recurrents.keys()" :key="recurrents[key].id"
         @click="router.push(`/recurrents/${recurrents[key].id}/edit`)"
         class="flex flex-col  w-full  pl-5  items-start justify-items-center font-bold  ">
      <div class="flex flex-row gap-2 w-full items-center justify-between">
        <div class="flex w-full flex items-center justify-between">
          <div class="flex flex-row items-center gap-2 ">
            <span class="text-4xl">{{ recurrents[key].category.icon }}</span>
            <div class="flex flex-col items-start">
              <div class="flex flex-row !font-bold "> {{ recurrents[key].name }}</div>
              <div class="flex flex-row text-sm">{{ recurrents[key].category.name }}</div>
            </div>
          </div>


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

  </div>
  </div>
</template>

<style scoped>

</style>