<script
    setup
    lang="ts"
>
    import { onMounted, ref } from 'vue';
    import { Bar } from 'vue-chartjs';
    import { useI18n } from 'vue-i18n';
    import { useQuasar, colors } from 'quasar';
    import { useTimesheetStore } from 'src/stores/timesheet-store';
    import { Chart as ChartJS, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale, TimeScale, type ChartDataset } from 'chart.js';

    const { t } = useI18n();
    const $q = useQuasar();

    ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale, TimeScale);
    ChartJS.defaults.font.family = '"Roboto", sans-serif';
    ChartJS.defaults.maintainAspectRatio = false;
    ChartJS.defaults.color = $q.dark.isActive ? '#F5F5F5' : '#616161';

    const timesheet_store = useTimesheetStore();

    const all_days = timesheet_store.timesheets.flatMap(week => week.days.flatMap(day => day.daily_expenses));

    const expenses_labels = ref<string[]>(timesheet_store.timesheets.flatMap(week => week.days.map(day => day.date.slice(-5,))));
    const expenses_dataset = ref<ChartDataset<'bar'>[]>([]);

    onMounted(() => {
        setTimeout(() => {
            expenses_dataset.value = [
                {
                    label: t('timesheet_approvals.table.expenses'),
                    data: all_days.map(day => (day.expenses + day.on_call + day.per_diem)),
                    backgroundColor: colors.getPaletteColor('accent'),
                },
                {
                    label: t('timesheet_approvals.table.mileage'),
                    data: all_days.map(day => day.mileage),
                    backgroundColor: colors.getPaletteColor('info'),
                }
            ]
        }, 100)
    });
</script>

<template>
    <div
        class="bg-dark rounded-10 q-pa-sm"
        :style="`min-height: ${$q.screen.lt.md ? '350px;' : '200px'}`"
    >
        <Bar
            :data="{
                datasets: expenses_dataset,
                labels: expenses_labels,
            }"
            :options="({
                indexAxis: $q.screen.lt.md ? 'y' : 'x',
                plugins: {
                    title: {
                        display: true,
                        text: t('timesheet_approvals.chart.expenses_title'),
                    },
                    legend: {
                        labels: {
                            boxWidth: 15,
                        }
                    }
                },
                scales: {
                    x: {
                        stacked: true
                    },
                    y: {
                        suggestedMin: 0,
                        suggestedMax: 100,
                        stacked: true
                    }
                }
            })"
        />
    </div>
</template>