<script setup lang="ts">
import { AccountApiClient, type Account, type CurrencyBalance } from '@/api/account'
import { formatMoney } from '@/api/data'
import { getSelectedProfile } from '@/api/profile'
import AccountCard from '@/components/AccountCard.vue'
import AppBadge from '@/components/common/AppBadge.vue'
import AppButton from '@/components/common/AppButton.vue'
import HomeModule from '@/components/HomeModule.vue'
import { onMounted, ref, type Ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const router = useRouter()
const route = useRoute()

const accounts: Ref<Account[]> = ref([])
const totalBalances: Ref<CurrencyBalance[]> = ref([])

onMounted(async () => {
  const accountApi = new AccountApiClient(route)
  accountApi.getAccounts().then(result => accounts.value = result)
    .catch(err => console.error(err))
  accountApi.getTotalBalances().then(result => {
    totalBalances.value = result
  })
    .catch(err => console.error(err))
})
</script>
<template>
  <HomeModule title="Accounts">
    <template v-slot:default>
      <AccountCard v-for="a in accounts" :account="a" :key="a.id" />
      <p v-if="accounts.length === 0">
        You haven't added any accounts. Add one to start tracking your finances.
      </p>

      <div>
        <AppBadge v-for="bal in totalBalances" :key="bal.currency.code">
          Total {{ bal.currency.code }}: {{ formatMoney(bal.balance, bal.currency) }}
        </AppBadge>
      </div>
    </template>
    <template v-slot:actions>
      <AppButton icon="plus" @click="router.push(`/profiles/${getSelectedProfile(route)}/add-account`)">Add Account
      </AppButton>
    </template>
  </HomeModule>
</template>
<style lang="css"></style>
