<template>
  <div class="chart-balance">
    <p>
      {{
        $tc('account.total', statOrdered.length, { count: statOrdered.length })
      }}
    </p>
    <table class="table is-hoverable is-striped" v-if="stats.length">
      <tbody>
        <tr v-for="(stat, k) in statOrdered" :key="k">
          <th scope="row">{{ stat.label }}</th>
          <td class="numeric">{{ stat.value | money(currency) }}</td>
          <td
            v-if="stat.balance.amount !== 0"
            class="numeric"
            :class="getColor(stat.balance.amount)"
          >
            {{ stat.balance.amount | money(currency) }}
          </td>
          <td
            v-else
            class="conclude"
            :class="getColor(stat.balance.amount)"
          ></td>
        </tr>
      </tbody>
      <tfoot>
        <tr :style="colorStyle">
          <th :style="colorStyle" scope="row" class="total">total</th>
          <th :style="colorStyle" class="numeric" colspan="2">
            {{ totalCost | money(currency) }}
          </th>
        </tr>
      </tfoot>
    </table>
    <div v-else>Aucune dépense faite</div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator'
import ICurrency from '@/models/ICurrency'
import IStat from '@/models/IStat'
import IAccount from '../models/IAccount'
import { findContrastColor } from '@/utils'

@Component({
  components: {
    'axis-label': () => import('@/components/AxisLabel.vue')
  }
})
export default class ChartBalance extends Vue {
  @Prop({ type: Object, required: true })
  public account!: IAccount
  @Prop({ type: Array, default: () => [] })
  public stats!: IStat[]
  @Prop({ type: Object, required: true })
  public currency!: ICurrency

  public getColor(amount: number): string {
    return amount === 0 ? 'zero' : amount > 0 ? 'positive' : 'negative'
  }

  public get colorStyle() {
    if (!this.account) {
      return {}
    }
    return {
      backgroundColor: this.account.color,
      color: findContrastColor(this.account.color)
    }
  }

  public get statOrdered(): IStat[] {
    return [...this.stats].sort((a: IStat, b: IStat) =>
      a.balance.amount < b.balance.amount ? 1 : -1
    )
  }

  public get totalCost(): number {
    return this.stats.reduce((a: number, b: IStat) => a + b.value, 0)
  }
}
</script>

<style lang="scss">
@import '../styles/variables';

.chart-balance {
  overflow-x: auto;
}
.table {
  margin: auto;
  .numeric {
    font-weight: bold;
    text-align: right;
  }
}
.zero {
  color: $primary;
  &.conclude::after {
    content: '👌🏾';
  }
}
.positive {
  color: $green;
}
.negative {
  color: $red;
}
</style>
