<script setup lang="ts">

import {onMounted, ref} from "vue";
import {Target} from "@/models/targets";
import {useRouter} from "vue-router";
import {useToolbarStore} from "@/stores/toolbar-store";
import {useSpaceStore} from "@/stores/spaceStore";
import {targetService} from "@/services/targets-service";
import {useToast} from "primevue/usetoast";
import {ProgressBar} from "primevue";
import {TargetTypeIcon, TargetTypeName} from "@/models/enums";
import {formatAmount} from "@/utils/utils";

const toast = useToast();

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

const targets = ref<Target[]>([])


const fetchData = async () => {
  try {
    if (spaceStore.selectedSpaceId) {
      targets.value = await targetService.fetchTargets(spaceStore.selectedSpaceId)
    }
  } catch (e) {
    console.error(e)
    toast.add({
      severity: 'error',
      summary: 'Failed to fetch target list.',
      detail: e.message
    })
  }
}

onMounted(async () => {
  await fetchData()
  toolbar.registerHandler('openTargetCreation', () => {
    router.push('/targets/create')
  })
})
</script>

<template>
  <div class="targets-list">
    <div v-for="target in targets" class="card  w-full">
      <div class="flex flex-col items-start justify-items-start justify-start w-full px-4 pb-4">
        <div class="flex flex-row items-center gap-2">
          <span class="text-4xl ">{{ TargetTypeIcon[target.type] }}</span>
          <div class="flex flex-col">
            <h2 class="text-2xl !font-semibold">{{ target.name }}</h2>
            <span class="text-sm text-gray-200"> {{ target.description }} | {{ TargetTypeName[target.type] }}</span>
          </div>
        </div>
        <div class="flex flex-col w-full">
          <div class="flex flex-row justify-between !w-full">
            <span> {{formatAmount(target.currentAmount)}} ₽</span>
            <span>{{formatAmount(target.amount)}} ₽</span>
          </div>
          <ProgressBar :value="((target.currentAmount / target.amount)*100).toFixed(0)" />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.targets-list {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  padding-bottom: 2.5rem;
}
</style>