import { DatePipe } from '@angular/common';
import { trigger, state, style, animate, transition } from '@angular/animations';
import { Component, DestroyRef, inject, OnInit, OnDestroy } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { ActivatedRoute } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatDividerModule } from '@angular/material/divider';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { Observable, Subscription } from 'rxjs';

import { MenuItems } from '@components/shared';
import { HistoryTableComponent } from '@components/shared/helpers-jump';
import { BarsChartComponent, PieChartComponent } from '@components/shared/helpers-chart';
import { Jump, CanopiesPageData } from '@models';
import { UtilitiesService } from '@services';
import { CanopyBySize, CanopyByYear, CanopyModelBySize, CanopyModelByYear } from '@models';

@Component({
    selector: 'app-canopies',
    imports: [
        DatePipe,
        MatButtonModule,
        MatCardModule,
        MatDividerModule,
        MatExpansionModule,
        MatGridListModule,
        MatIconModule,
        MatMenuModule,
        HistoryTableComponent,
        BarsChartComponent,
        PieChartComponent,
    ],
    templateUrl: './canopies.component.html',
    styleUrl: './canopies.component.scss',
    animations: [
        trigger('flyInOut', [
            state('in', style({ transform: 'translateX(0)' })),
            transition('void => *', [style({ transform: 'translateX(-100%)' }), animate(200)]),
            transition('* => void', [style({ transform: 'translateX(100%)' }), animate(200)]),
        ]),
    ],
})
export class CanopiesComponent implements OnInit, OnDestroy {
    private route = inject(ActivatedRoute);
    private _utilitiesService = inject(UtilitiesService);
    menuItems = inject(MenuItems);

    private _data: Subscription = new Subscription();
    private _canopiesModelBySize!: Array<CanopyModelBySize>;
    private _canopiesModelByYear!: Array<CanopyModelByYear>;
    private _canopiesSizeBySize!: Array<CanopyBySize>;
    private _canopiesSizeByYear!: Array<CanopyByYear>;
    public lastJump: Jump = {} as Jump;
    public title = 'Voiles';
    public subtitle: string = 'Nombre total de sauts par modèle et taille';
    public displayCharts = false;
    public destroyRef = inject(DestroyRef);
    public seriesModelHeader: string[] = [];
    public seriesModelName: string[] = [];
    public seriesModelValue: number[] = [];
    public seriesModelRow: Array<Array<number>> = [];
    public seriesSizeHeader: string[] = [];
    public seriesSizeName: string[] = [];
    public seriesSizeValue: number[] = [];
    public seriesSizeRow: Array<Array<number>> = [];
    public seriesColor: {
        backgroundColor: string[];
        borderColor: string[];
    } = {
        backgroundColor: this._utilitiesService.getSeriesColors(0.8, 'all'),
        borderColor: this._utilitiesService.getSeriesColors(1, 'all'),
    };
    public seriesColorClass: string[] = this._utilitiesService.getChartColors();

    ngOnInit() {
        const data$: Observable<{ canopiesPageData: CanopiesPageData }> = this.route.data as Observable<{
            canopiesPageData: CanopiesPageData;
        }>;
        this._data = data$
            .pipe(takeUntilDestroyed(this.destroyRef))
            .subscribe((data: { canopiesPageData: CanopiesPageData }) => {
                const pageData: CanopiesPageData = data.canopiesPageData;
                this.lastJump = pageData.lastjump;
                this._loadCanopyBySize(pageData);
                this._loadCanopyModelBySize(pageData);
            });
    }

    ngOnDestroy() {
        this._data.unsubscribe();
    }

    private _loadCanopyBySize(pageData: CanopiesPageData): void {
        this._canopiesSizeBySize = pageData.canopiesBySize.map((row: CanopyBySize) => {
            this.seriesSizeName.push(row.taille.toString());
            this.seriesSizeValue.push(row.count);
            return row;
        });
        this._loadCanopyByYear(pageData);
    }

    private _loadCanopyByYear(pageData: CanopiesPageData): void {
        this.seriesSizeHeader = ['2018', '2019', '2020', '2021', '2022', '2023', '2024'];
        const values: Array<number> = this.seriesSizeHeader.map(() => 0);
        this.seriesSizeName.forEach(() => {
            this.seriesSizeRow.push([...values]);
        });
        this._canopiesSizeByYear = pageData.canopiesBySizeByYear.map((row: CanopyByYear) => {
            const taille: string = row.taille.toString();
            const year: string = row.year.toString();
            this.seriesSizeRow[this.seriesSizeName.indexOf(taille)][this.seriesSizeHeader.indexOf(year)] = row.count;
            return row;
        });
    }

    private _loadCanopyModelBySize(pageData: CanopiesPageData): void {
        this._canopiesModelBySize = pageData.canopiesBySizeByModel.map((row: CanopyModelBySize) => {
            this.seriesModelName.push(`${row.taille.toString()} - ${row.voile}`);
            this.seriesModelValue.push(row.count);
            return row;
        });
        this._loadCanopyModelByYear(pageData);
    }

    private _loadCanopyModelByYear(pageData: CanopiesPageData): void {
        this.seriesModelHeader = ['2018', '2019', '2020', '2021', '2022', '2023', '2024'];
        const values: Array<number> = this.seriesModelHeader.map(() => 0);
        this.seriesModelName.forEach(() => {
            this.seriesModelRow.push([...values]);
        });
        this._canopiesModelByYear = pageData.canopiesBySizeByModelByYear.map((row: CanopyModelByYear) => {
            const voile: string = row.voile;
            const taille: string = row.taille.toString();
            const year: string = row.year.toString();
            this.seriesModelRow[this.seriesModelName.indexOf(`${taille} - ${voile}`)][
                this.seriesModelHeader.indexOf(year)
            ] = row.count;
            return row;
        });
        this.displayCharts = true;
    }
}
