<script setup lang="ts">
import { AccountTypes, type Account } from '@/api/account'
import { formatMoney } from '@/api/data'
import { getSelectedProfile } from '@/api/profile'
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import AppBadge from './common/AppBadge.vue'

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

const props = defineProps<{ account: Account }>()
const accountType = computed(() => AccountTypes.of(props.account.type))
const isBalancePositive = computed(() => {
  return (
    props.account.currentBalance !== null &&
    (accountType.value.debitsPositive
      ? props.account.currentBalance > 0
      : props.account.currentBalance < 0)
  )
})
const isBalanceNegative = computed(() => {
  return (
    props.account.currentBalance !== null &&
    (accountType.value.debitsPositive
      ? props.account.currentBalance < 0
      : props.account.currentBalance > 0)
  )
})

function goToAccount() {
  const profile = getSelectedProfile(route)
  router.push(`/profiles/${profile}/accounts/${props.account.id}`)
}
</script>
<template>
  <div
    class="account-card"
    @click="goToAccount()"
  >
    <!-- A top row for the name on the left, and balance on the right. -->
    <div class="account-card-top-row">
      <div>
        <span
          class="font-bold"
          style="margin-right: 0.5rem"
          >{{ account.name }}</span
        >
        <span class="font-mono font-size-xsmall">#{{ account.numberSuffix }}</span>
      </div>

      <div
        class="font-mono font-size-small"
        :class="{
          'text-positive': isBalancePositive,
          'text-negative': isBalanceNegative,
        }"
      >
        <span v-if="account.currentBalance !== null">
          {{ formatMoney(account.currentBalance, account.currency) }}
        </span>
        <span v-if="account.currentBalance === null">-</span>
        <span>&nbsp;{{ account.currency.code }}</span>
      </div>
    </div>
    <!-- A bottom row for other attributes. -->
    <div>
      <AppBadge size="sm">{{ accountType.emoji }} {{ accountType.name }}</AppBadge>
    </div>
  </div>
</template>
<style lang="css">
.account-card {
  background-color: var(--bg);
  padding: 0.5rem;
  border-radius: 0.5rem;
  margin: 0.5rem 0;
  cursor: pointer;
}

.account-card:hover {
  background-color: var(--bg-darker);
}

.account-card-top-row {
  display: flex;
  justify-content: space-between;
}
</style>
