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() ticksCallback?: (value: number) => string;
    @Input() secondaryAxis = false;
    @Input() yAxisLabel?: string;
    @Input() yAxisLabelRight?: string;

    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 = {
            scales: {
                y: {
                    stacked: true,
                    ticks: { callback: this.ticksCallback ? (value: number) => this.ticksCallback(value) : undefined },
                    title: {
                        display: !!this.yAxisLabel,
                        text: this.yAxisLabel,
                        padding: { bottom: 20 },
                    },
                },
                y1: {
                    display: this.secondaryAxis,
                    position: 'right',
                    title: {
                        display: !!this.yAxisLabelRight,
                        text: this.yAxisLabelRight,
                        padding: { bottom: 20 },
                    },
                },
            },
            plugins: {
                legend: { position: 'right' },
                tooltip: {
                    callbacks: {
                        label: this.ticksCallback ? item => `${item.dataset.label}: ${this.ticksCallback(item.parsed.y)}` : undefined,
                    },
                },
            },
            layout: {
                padding: {
                    top: 50,
                    bottom: 50,
                },
            },
            datasets: { bar: { barPercentage: 0.7 } },
            aspectRatio: 2.5,
        };
    }
}
