import { Component, Input, OnChanges } from '@angular/core';
import { ChartConfiguration, ChartDataset } from 'chart.js';

@Component({
    selector: 'redaction-chart',
    templateUrl: './chart.component.html',
    styleUrls: ['./chart.component.scss'],
})
export class ChartComponent implements OnChanges {
    @Input({ required: true }) datasets: ChartDataset[];
    @Input({ required: true }) labels: string[];
    @Input() valueFormatter?: (value: number) => string;
    @Input() secondaryAxis = false;
    @Input() yAxisLabel?: string;
    @Input() yAxisLabelRight?: string;
    @Input() reverseLegend = false;

    chartData: ChartConfiguration['data'];
    chartOptions: ChartConfiguration<'line'>['options'] = {};

    constructor() {
        this.#setChartOptions();
    }

    ngOnChanges() {
        this.chartData = {
            labels: this.labels,
            datasets: this.datasets,
        };
        this.#setChartOptions();
    }

    #setChartOptions(): void {
        this.chartOptions = {
            responsive: false,
            scales: {
                y: {
                    stacked: true,
                    ticks: {
                        callback: this.valueFormatter ? (value: number) => this.valueFormatter(value) : undefined,
                        count: 9,
                    },
                    title: {
                        display: !!this.yAxisLabel,
                        text: this.yAxisLabel,
                        padding: { bottom: 20 },
                    },
                    min: 0,
                },
                y1: {
                    display: this.secondaryAxis,
                    position: 'right',
                    ticks: {
                        callback: this.valueFormatter ? (value: number) => this.valueFormatter(value) : undefined,
                        count: 9,
                    },
                    title: {
                        display: !!this.yAxisLabelRight,
                        text: this.yAxisLabelRight,
                        padding: { bottom: 20 },
                    },
                    min: 0,
                },
            },
            plugins: {
                legend: { position: 'right', reverse: this.reverseLegend, maxWidth: 280 },
                tooltip: {
                    callbacks: {
                        label: this.valueFormatter ? item => `${item.dataset.label}: ${this.valueFormatter(item.parsed.y)}` : undefined,
                    },
                },
            },
            layout: {
                padding: {
                    top: 50,
                    bottom: 50,
                },
            },
            datasets: { bar: { barPercentage: 0.7 } },
            aspectRatio: 2.5,
        };
    }
}
