<script setup lang="ts">
import { computed } from 'vue'
import type IAccount from '@/models/IAccount'
import type ICurrency from '@/models/ICurrency'
import type IStat from '@/models/IStat'
import { findContrastColor } from '@/utils'
import { money } from '@/utils/format'

const props = defineProps<{
  account: IAccount
  stats: IStat[]
  currency: ICurrency
}>()

const statOrdered = computed(() =>
  [...props.stats].sort((a, b) => (a.balance.amount < b.balance.amount ? 1 : -1))
)

const totalCost = computed(() =>
  props.stats.reduce((a, b) => a + b.value, 0)
)

const colorStyle = computed(() => {
  if (!props.account) return {}
  return {
    backgroundColor: props.account.color ?? undefined,
    color: findContrastColor(props.account.color ?? null) ?? undefined
  }
})

const getColor = (amount: number): string =>
  amount === 0 ? 'text-primary' : amount > 0 ? 'text-success' : 'text-error'
</script>

<template>
  <div class="chart-balance overflow-x-auto">
    <table v-if="stats.length" class="table table-zebra mx-auto">
      <tbody>
        <tr v-for="(stat, k) in statOrdered" :key="k">
          <th scope="row">{{ stat.label }}</th>
          <td class="numeric font-bold text-right">{{ money(stat.value, currency) }}</td>
          <td
            v-if="stat.balance.amount !== 0"
            class="numeric font-bold text-right"
            :class="getColor(stat.balance.amount)"
          >
            {{ money(stat.balance.amount, currency) }}
          </td>
          <td v-else class="text-right" :class="getColor(stat.balance.amount)">
            👌🏾
          </td>
        </tr>
      </tbody>
      <tfoot>
        <tr :style="colorStyle">
          <th :style="colorStyle" scope="row" class="font-bold">total</th>
          <th :style="colorStyle" class="numeric text-right" colspan="2">
            {{ money(totalCost, currency) }}
          </th>
        </tr>
      </tfoot>
    </table>
    <div v-else>Aucune dépense faite</div>
  </div>
</template>
