import { Component, computed, effect, input, signal } from '@angular/core';
import { EChartsOption } from 'echarts';
import { GaugeChart } from 'echarts/charts';
import { ECharts } from 'echarts/core';
import { UtilNgxEchartsModule } from '../../ngx-echarts/util-ngx-echarts.module';

@Component({
  selector: 'app-gauge-chart',
  imports: [UtilNgxEchartsModule],
  template: ` <div
    dksEcharts
    [defaultHeight]="75"
    [options]="options()"
    [extentions]="extentions()"
    (chartInit)="setChartInstance($event)"
  ></div>`,
  styles: ``,
})
export class GaugeChartComponent {
  private chart?: ECharts;

  value = input.required<number>();
  options = computed<EChartsOption>(() => ({
    series: [
      {
        type: 'gauge',
        center: ['50%', '100%'],
        startAngle: 180,
        endAngle: -40,
        radius: '200%',
        min: 0,
        max: 100,
        progress: {
          show: true,
          width: 4,
        },
        pointer: {
          show: false,
        },
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          show: false,
        },
        axisLabel: {
          show: false,
        },
        detail: {
          valueAnimation: true,
          width: '100%',
          lineHeight: 20,
          borderRadius: 8,
          offsetCenter: [0, '-30%'],
          fontSize: 28,
          fontWeight: 'normal',
          formatter: '{value}%',
          color: 'inherit',
        },
        data: [
          {
            value: this.value(),
          },
        ],
      },
    ],
  }));
  extentions = signal([GaugeChart]);

  constructor() {
    effect(() => {
      if (!!this.chart) {
        this.chart.setOption({
          series: [
            {
              data: [
                {
                  value: this.value(),
                },
              ],
            },
          ],
        });
      }
    });
  }

  setChartInstance(chart: ECharts) {
    this.chart = chart;
  }
}
