<script
    setup
    lang="ts"
>
    import { ref } from 'vue';
    import { Bar } from 'vue-chartjs';
    import { useI18n } from 'vue-i18n';
    import { useQuasar } from 'quasar';
    import { useTimesheetStore } from 'src/stores/timesheet-store';
    import { Chart as ChartJS, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale, TimeScale, type ChartData, 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 expenses_dataset = ref<ChartDataset<'bar'>[]>([]);
    const expenses_labels = ref<string[]>([]);

    const getExpensesData = (): ChartData<'bar'> => {
        const all_days = timesheet_store.pay_period_details.weeks.flatMap(week => Object.values(week.expenses));
        const all_days_dates = timesheet_store.pay_period_details.weeks.flatMap(week => Object.values(week.shifts))

        const all_costs = all_days.map(day => day.total_expenses);
        const all_mileage = all_days.map(day => day.total_mileage);


        expenses_dataset.value = [
            {
                label: t('timesheet_approvals.table.expenses'),
                data: all_costs,
                backgroundColor: getComputedStyle(document.body).getPropertyValue('--q-primary').trim(),
            },
            {
                label: t('timesheet_approvals.table.mileage'),
                data: all_mileage,
                backgroundColor: getComputedStyle(document.body).getPropertyValue('--q-info').trim(),
            }
        ]

        expenses_labels.value = all_days_dates.map(day => day.short_date);

        return {
            datasets: expenses_dataset.value,
            labels: expenses_labels.value
        };
    };
</script>

<template>
    <div>
        <Bar
            :data="getExpensesData()"
            :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>