import { Component } from '@angular/core';
import { format, Interval } from 'date-fns';
import { BehaviorSubject, combineLatest, map } from 'rxjs';
import { ManagerDashboardService } from '../manager-dashboard.service';
import { OrdinanceTypes } from '../types';

@Component({
    selector: 'dks-overview',
    templateUrl: './overview.component.html',
    styleUrls: ['./overview.component.css'],
    standalone: false
})
export class OverviewComponent {
  OrdinanceTypes = OrdinanceTypes;
  selectedOrdinanceType$ = new BehaviorSubject<OrdinanceTypes | undefined>(
    undefined
  );
  vm$;

  constructor(
    private readonly managerDashboardService: ManagerDashboardService
  ) {
    this.vm$ = combineLatest([
      this.managerDashboardService.getTimePerTourKPIByOrdinanceTypes(
        OrdinanceTypes.BTW
      ),
      this.managerDashboardService.getTimePerTourKPIByOrdinanceTypes(
        OrdinanceTypes.TSW
      ),
      this.managerDashboardService.getTimePerTourKPIByOrdinanceTypes(
        OrdinanceTypes.KTW
      ),
      this.selectedOrdinanceType$,
    ]).pipe(
      map(([btwKPIs, tswKPIs, ktwKPIs, selectedOrdinanceType]) => ({
        btwKPI: {
          summaries: btwKPIs.map(({ interval, kpi }) => ({ interval, kpi })),
          cars: this.createCarTableData(
            btwKPIs.map(({ interval, cars }) => ({ interval, cars }))
          ),
        },
        tswKPI: {
          summaries: tswKPIs.map(({ interval, kpi }) => ({ interval, kpi })),
          cars: this.createCarTableData(
            tswKPIs.map(({ interval, cars }) => ({ interval, cars }))
          ),
        },
        ktwKPI: {
          summaries: ktwKPIs.map(({ interval, kpi }) => ({ interval, kpi })),
          cars: this.createCarTableData(
            ktwKPIs.map(({ interval, cars }) => ({ interval, cars }))
          ),
        },
        selectedOrdinanceType,
      }))
    );
  }

  setSelectedOrdinanceType(ordinanceType: OrdinanceTypes): void {
    if (this.selectedOrdinanceType$.getValue() === ordinanceType) {
      this.selectedOrdinanceType$.next(undefined);
    } else {
      this.selectedOrdinanceType$.next(ordinanceType);
    }
  }

  private createCarTableData(
    carsByInterval: {
      interval: Interval;
      cars: {
        carName: string;
        kpi: {
          value: number;
          meta: { availableTime: number; tourAmount: number };
        };
      }[];
    }[]
  ) {
    const columns = [
      { id: 'carName', title: 'Fahrzeug' },
      ...carsByInterval.map(({ interval }, index) => ({
        id: `slot${index}`,
        title: `${format(new Date(interval.start), 'HH:mm')} - ${format(
          new Date(interval.end),
          'HH:mm'
        )}`,
      })),
    ];
    const groupedByCars = carsByInterval.reduce(
      (grouped, carsWithInterval, index) => {
        const { cars } = carsWithInterval;
        let newGroup = { ...grouped };
        for (const car of cars) {
          newGroup = {
            ...newGroup,
            [car.carName]: {
              carName: car.carName,
              ...(newGroup[car.carName] ?? {}),
              [`slot${index}`]: car.kpi.value,
              additionalData: [
                ...(newGroup[car.carName]?.additionalData ?? []),
                car.kpi.meta,
              ],
            },
          };
        }
        return newGroup;
      },
      {} as Record<string, any>
    );
    return { columns, data: Object.values(groupedByCars) };
  }
}
