<template>
  <WidgetShell title="Total depreciation by book" icon="mdi-chart-bar-stacked" :loading="loading" :editing="editing" @refresh="load" @remove="$emit('remove')">
    <div v-if="rows.length" style="height:200px"><Bar :data="chartData" :options="opts" /></div>
    <div v-else-if="!loading" class="quiet text-body-2">No accumulated depreciation yet.</div>
  </WidgetShell>
</template>
<script>
import WidgetShell from './WidgetShell.vue';
import { Bar } from 'vue-chartjs';
import '../../utils/charts';
import { apiRequest } from '../../services/api';
export default {
  components: { WidgetShell, Bar },
  props: { token: { type: String, required: true }, editing: { type: Boolean, default: false }, config: { type: Object, default: () => ({}) } },
  emits: ['remove'],
  data() { return { loading: false, rows: [], opts: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true, ticks: { callback: (v) => '$' + Number(v).toLocaleString() } } } } }; },
  computed: { chartData() { return { labels: this.rows.map((r) => r.book), datasets: [{ data: this.rows.map((r) => r.accumulated), backgroundColor: '#3f9d5a' }] }; } },
  mounted() { this.load(); },
  methods: {
    async load() {
      this.loading = true;
      try { this.rows = (await (await apiRequest('/api/dashboard/depreciation', this.token)).json()).byBook.filter((r) => r.accumulated); }
      catch { this.rows = []; } finally { this.loading = false; }
    }
  }
};
</script>
