import {
  AfterViewInit,
  Component,
  ElementRef,
  OnDestroy,
  ViewChild,
} from '@angular/core';
import { Chart, ChartOptions } from 'chart.js/auto';
import { PluginNodata } from './plugin-nodata';
import { PluginMoreColors } from './plugin-more-colors';
import { ChartType, IData } from './chart-type';

@Component({
  selector: 'fbi-chart',
  standalone: true,
  imports: [],
  templateUrl: './chart.component.html',
  styleUrl: './chart.component.scss',
})
export class ChartComponent implements AfterViewInit, OnDestroy {
  @ViewChild('chart') canvas!: ElementRef;

  private chart: any = undefined;
  private data: IData = {
    labels: Array.from(
      { length: 10 },
      () => `${Math.floor(Math.random() * 100)}`
    ),
    // labelsSource: [],
    datasets: [
      {
        label: 'test',
        data: Array.from(
          { length: 10 },
          () => `${Math.floor(Math.random() * 100)}`
        ),
      },
    ],
  };

  constructor() {}

  ngAfterViewInit(): void {
    this.initChart();
  }

  ngOnDestroy(): void {
    this.chart?.destroy?.();
  }

  initChart() {
    this.chart?.destroy?.();

    const opts: ChartOptions = {};
    opts.responsive = true;
    opts.maintainAspectRatio = false;

    this.chart = new Chart(this.canvas.nativeElement, {
      type: ChartType.Bar,
      data: this.data,
      options: opts,
      plugins: [PluginNodata.config(), PluginMoreColors.config()] as any[],
    });
  }
}
