import { Component, Input, OnChanges, AfterContentChecked, inject } from '@angular/core';
import { ChartDataset } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';

import { UtilitiesService } from '@services';
import { BarConfig } from '@models';

@Component({
    selector: 'app-bars-chart',
    imports: [BaseChartDirective],
    templateUrl: './bars-chart.component.html',
})
export class BarsChartComponent implements OnChanges, AfterContentChecked {
    private _utilitiesService = inject(UtilitiesService);

    public displayCharts = false;
    public chartConfig: BarConfig = this._utilitiesService.getBarChartConfig();

    @Input() names: string[] = [];
    @Input() values: Array<Array<number>> = [];
    @Input() headers: string[] = [];
    @Input() colors: {
        backgroundColor: string[];
        borderColor: string[];
    } = {
        backgroundColor: this._utilitiesService.getSeriesColors(0.8),
        borderColor: this._utilitiesService.getSeriesColors(1),
    };
    @Input() legend: boolean = false;

    ngOnChanges() {
        this._loadBarChart();
    }

    ngAfterContentChecked() {
        this._loadBarChart();
    }

    private _loadBarChart(): void {
        this.chartConfig = this._utilitiesService.getBarChartConfig();
        this.chartConfig.barChartData.labels = [...this.headers];
        this.chartConfig.barChartOptions!.maintainAspectRatio = false;
        //this.chartConfig.barChartOptions!.aspectRatio = 2.4;
        this.chartConfig.barChartOptions!.scales = {
            x: {
                display: true,
                //stacked: true,
                beginAtZero: true,
                ticks: { color: 'rgba(255,255,255,0.3)' },
                grid: {
                    color: 'rgba(255,255,255,0.1)',
                    display: true,
                    tickBorderDash: [1, 2],
                    tickBorderDashOffset: 2,
                },
            },
            y: {
                display: true,
                //stacked: true,
                beginAtZero: true,
                ticks: { color: 'rgba(255,255,255,0.3)' },
                grid: {
                    color: 'rgba(255,255,255,0.2)',
                    tickBorderDash: [1, 2],
                    tickBorderDashOffset: 2,
                    display: true,
                },
            },
        };
        this.names.forEach((label: string, index: number) => {
            const dataset: ChartDataset<'bar'> = {
                data: [...this.values[index]],
                label: label,
                backgroundColor: this.colors.backgroundColor[index],
                borderColor: this.colors.borderColor[index],
                borderWidth: 1,
                //stack: 'Stack 0'
            };
            this.chartConfig.barChartData.datasets!.push(dataset);
        });
        this.chartConfig.barChartLegend = this.legend;
        this.displayCharts = true;
    }
}
