<script setup lang="ts">
import { AccountApiClient, AccountTypes, 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 { computed, 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([])
// Computed total amount of debt per currency.
const totalOwed: Ref<CurrencyBalance[]> = computed(() => {
  const totals: CurrencyBalance[] = []
  for (const acc of accounts.value) {
    if (acc.currentBalance === null) continue
    if (totals.filter((t) => t.currency.code === acc.currency.code).length === 0) {
      totals.push({ balance: 0, currency: acc.currency })
    }
    const currencyTotal = totals.filter((t) => t.currency.code === acc.currency.code)[0]
    const accountType = AccountTypes.of(acc.type)
    if (
      (accountType.debitsPositive && acc.currentBalance < 0) ||
      (!accountType.debitsPositive && acc.currentBalance > 0)
    ) {
      currencyTotal.balance += acc.currentBalance
    }
  }
  return totals
})

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))
})

function exportAccounts() {
  const api = new AccountApiClient(route)
  api.downloadAccountsExport()
}
</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"
        >
          {{ bal.currency.code }} Total:
          <span class="font-mono">{{ formatMoney(bal.balance, bal.currency) }}</span>
        </AppBadge>
        <AppBadge
          v-for="debt in totalOwed"
          :key="debt.currency.code"
        >
          {{ debt.currency.code }} Debt:
          <span
            class="font-mono"
            :class="{ 'text-negative': debt.balance > 0 }"
            >{{ formatMoney(debt.balance, debt.currency) }}</span
          >
        </AppBadge>
      </div>
    </template>
    <template v-slot:actions>
      <AppButton
        icon="plus"
        @click="router.push(`/profiles/${getSelectedProfile(route)}/add-account`)"
        >Add Account
      </AppButton>
      <AppButton
        icon="download"
        size="sm"
        @click="exportAccounts()"
      >
        Export
      </AppButton>
    </template>
  </HomeModule>
</template>
<style lang="css"></style>
