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 { GoogleMap, MapKmlLayer } from '@angular/google-maps';
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 { ChartistModule, Configuration } from 'ng-chartist';
//import { AxisOptions, Label } from 'chartist';
import { Observable, Subscription } from 'rxjs';

import { MenuItems } from '@components/shared';
import { BarsChartComponent, PieChartComponent } from '@components/shared/helpers-chart';
import { HistoryTableComponent } from '@components/shared/helpers-jump';
import { DropZoneByOaci, DropZoneByYear, DropZonesPageData, Jump } from '@models';
import { UtilitiesService } from '@services';

@Component({
    selector: 'app-dropzones',
    imports: [
        DatePipe,
        GoogleMap,
        MapKmlLayer,
        MatButtonModule,
        MatCardModule,
        MatDividerModule,
        MatExpansionModule,
        MatGridListModule,
        MatIconModule,
        MatMenuModule,
        //ChartistModule,
        HistoryTableComponent,
        BarsChartComponent,
        PieChartComponent,
    ],
    templateUrl: './dropzones.component.html',
    styleUrl: './dropzones.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 DropzonesComponent implements OnInit, OnDestroy {
    private route = inject(ActivatedRoute);
    private _utilitiesService = inject(UtilitiesService);
    menuItems = inject(MenuItems);

    private _data: Subscription = new Subscription();
    private _lastjump: Subscription = new Subscription();
    private _dropzonesByOaci!: Array<DropZoneByOaci>;
    private _dropzonesByYear!: Array<DropZoneByYear>;
    public lastJump: Jump = {} as Jump;
    public title = 'Drop zones';
    public subtitle: string = 'Nombre total de sauts par drop zone';
    public displayCharts = false;
    public destroyRef = inject(DestroyRef);
    public seriesHeader: string[] = [];
    public seriesName: string[] = [];
    public seriesValue: number[] = [];
    public seriesRow: 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();
    //public chartBarConfig: Configuration = this._utilitiesService.getBarConfig();

    public center: google.maps.LatLngLiteral = { lat: 44.596408, lng: -1.115958 };
    public zoom = 16;
    public kmlUrl = 'https://rampeur.com/assets/kmls/dropzones.kml?v=6';
    //public mapTypeId: google.maps.MapTypeId = google.maps.MapTypeId.SATELLITE;
    public options: google.maps.MapOptions = {
        //zoomControl: false,
        //scrollwheel: false,
        //mapTypeId: google.maps.MapTypeId.SATELLITE,
        mapTypeId: 'satellite',
        disableDoubleClickZoom: true,
        maxZoom: 20,
        minZoom: 3,
    };

    ngOnInit() {
        const data$: Observable<{ dropZonesPageData: DropZonesPageData }> = this.route.data as Observable<{
            dropZonesPageData: DropZonesPageData;
        }>;
        this._data = data$
            .pipe(takeUntilDestroyed(this.destroyRef))
            .subscribe((data: { dropZonesPageData: DropZonesPageData }) => {
                const pageData: DropZonesPageData = data.dropZonesPageData;
                this.lastJump = pageData.lastjump;
                this._loadDropZoneByOaci(pageData);
            });
    }

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

    private _loadDropZoneByOaci(pageData: DropZonesPageData): void {
        this._dropzonesByOaci = pageData.dropZonesByOaci.map((row: DropZoneByOaci) => {
            this.seriesName.push(`${row.oaci} - ${row.lieu}`);
            this.seriesValue.push(row.count);
            return row;
        });
        this._loadDropZoneByYear(pageData);
    }

    private _loadDropZoneByYear(pageData: DropZonesPageData): void {
        this.seriesHeader = ['2018', '2019', '2020', '2021', '2022', '2023', '2024'];
        const values: Array<number> = this.seriesHeader.map(() => 0);
        this.seriesName.forEach(() => {
            this.seriesRow.push([...values]);
        });
        this._dropzonesByYear = pageData.dropZonesByOaciByYear.map((row: DropZoneByYear) => {
            const lieu: string = row.lieu;
            const oaci: string = row.oaci;
            const year: string = row.year.toString();
            this.seriesRow[this.seriesName.indexOf(`${oaci} - ${lieu}`)][this.seriesHeader.indexOf(year)] = row.count;
            return row;
        });
        /*
        const axisX: AxisOptions = {
            labelInterpolationFnc: function(value: Label, index: number): string {
                return index % 1 === 0 ? `${value.toString()}` : '';
            }
        }
        this.chartBarConfig = {
            type: 'Bar',
            data: {
                'labels': this.seriesHeader,
                'series': this.seriesRow
            },
            options: {
                seriesBarDistance: 15,
                horizontalBars: false,
                high: 180,
                axisX: {
                    showGrid: false,
                    offset: 20
                },
                axisY: {
                    showGrid: true,
                    offset: 40
                },
                height: 300
            },
            responsiveOptions: [
                ['screen and (min-width: 1024px)', {
                    axisX: axisX
                }],
                ['screen and (min-width: 641px) and (max-width: 1024px)', {
                    seriesBarDistance: 7,
                    axisY: {
                        offset: 30
                    },
                    axisX: axisX
                }],
                ['screen and (max-width: 640px)', {
                    seriesBarDistance: 5,
                    axisY: {
                        offset: 20
                    },
                    axisX: axisX
                }]
            ]
        };
        */
        this.displayCharts = true;
    }
}
