import { CommonModule } from '@angular/common';
import { Component, Input, OnChanges } from '@angular/core';
import { format } from 'date-fns';
import { EChartsOption, LegendComponentOption } from 'echarts';
import { BarChart, LineChart } from 'echarts/charts';
import {
  GridComponent,
  LegendComponent,
  TooltipComponent,
} from 'echarts/components';
import { BehaviorSubject } from 'rxjs';
import { UtilNgxEchartsModule } from '../../../../core/components/ngx-echarts/util-ngx-echarts.module';
import { TimePerTourMetric } from '../../../../core/data-access/graphql/generated/generated';

@Component({
    selector: 'dks-average-revenue-metric',
    imports: [CommonModule, UtilNgxEchartsModule],
    templateUrl: './average-revenue-metric.component.html',
    styleUrls: ['./average-revenue-metric.component.css']
})
export class AverageRevenueMetricComponent implements OnChanges {
  @Input() metrics: TimePerTourMetric[] = [];
  @Input() labelFormat!: string;

  echartsExtensions = [
    BarChart,
    LineChart,
    TooltipComponent,
    GridComponent,
    LegendComponent,
  ];

  echartsOptions$: BehaviorSubject<EChartsOption> = new BehaviorSubject(
    this.generateEChartsOptions(this.metrics)
  );

  ngOnChanges(): void {
    this.echartsOptions$.next(this.generateEChartsOptions(this.metrics));
  }

  private generateEChartsOptions(metrics: TimePerTourMetric[]): EChartsOption {
    const legendData = ['Durchschnittsumsatz', 'Index'];

    const legendOptions: LegendComponentOption = {
      orient: 'horizontal',
      data: legendData,
    };

    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      grid: {
        left: '15%',
        width: '80%',
        bottom: 50,
      },
      legend: legendOptions,
      xAxis: [
        {
          type: 'category',
          axisTick: {
            show: true,
            alignWithLabel: true,
          },
          axisLabel: {
            rotate: 30,
            interval: 1,
            fontSize: 10,
          },
          data: metrics.map(({ interval: { start } }) =>
            format(new Date(start), this.labelFormat)
          ),
        },
      ],
      yAxis: [
        {
          type: 'value',
          name: 'Betrag (EUR)',
          position: 'left',
          alignTicks: true,
          axisLine: {
            show: true,
          },
          minInterval: 1,
          axisLabel: {
            fontSize: 10,
          },
        },
        {
          type: 'value',
          name: 'Index',
          position: 'right',
          alignTicks: true,
          axisLine: {
            show: true,
          },
          interval: 2,
          min: 0,
          max: 10,
          axisLabel: {
            fontSize: 10,
          },
        },
      ],
      series: [
        {
          name: 'Index',
          type: 'line',
          data: metrics.map(({ tourAmount, availableTime }) => {
            let value = 0;
            if (tourAmount <= 0) {
              value = availableTime / 0.1;
            } else {
              value = availableTime / tourAmount;
            }
            return {
              value: value.toFixed(2),
              itemStyle: {
                borderWidth: 10,
              },
            };
          }),
          symbol: 'none',
          symbolSize: 1,
          smooth: true,
          yAxisIndex: 1,
        },
        {
          name: 'Durchschnittsumsatz',
          type: 'bar',
          data: metrics.map(({ averageRevenue }) => averageRevenue.toFixed(2)),
          itemStyle: {
            borderRadius: [5, 5, 0, 0],
          },
          barWidth: 8,
          yAxisIndex: 0,
        },
      ],
    };
  }
}
