import { Component, DestroyRef, inject, OnInit, OnDestroy } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { DatePipe, DecimalPipe } from '@angular/common';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { Observable, Subscription } from 'rxjs';

import { MenuItems } from '@components/shared';
import { Errors, Jump, JumpPageData } from '@models';

@Component({
    selector: 'app-jump',
    imports: [
        DatePipe,
        DecimalPipe,
        RouterLink,
        MatButtonModule,
        MatCardModule,
        MatDividerModule,
        MatIconModule,
        MatMenuModule,
    ],
    templateUrl: './jump.component.html',
    styleUrl: './jump.component.scss',
})
export class JumpComponent implements OnInit, OnDestroy {
    private route = inject(ActivatedRoute);
    menuItems = inject(MenuItems);

    private _data: Subscription = new Subscription();
    public title: string = '';
    public errors: Errors = { errors: {} };
    public destroyRef = inject(DestroyRef);
    public jump: Jump = { sautants: [], author: {} } as unknown as Jump;
    public prevSlug: string = '';
    public nextSlug: string = '';

    ngOnInit() {
        const data$: Observable<{ pageData: JumpPageData }> = this.route.data as Observable<{ pageData: JumpPageData }>;
        this._data = data$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((data: { pageData: JumpPageData }) => {
            this.jump = data.pageData.jump;
            this.prevSlug = data.pageData.prevJump?.slug;
            this.nextSlug = data.pageData.nextJump?.slug;
            this.title = `Saut n° ${this.jump.numero} `;
        });
        /*
        const data$: Observable<Jump> = this.route.data as Observable<Jump>;
        this._data = data$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((data: Jump) => {
            this.jump = data;
            console.log('jump : ', this.jump);
        });
        */
    }

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

    formatDuration(duration: number): string {
        const start = new Date(0);
        start.setSeconds(duration);
        return start.toISOString().substring(14, 19);
    }

    private _resetErrors(): void {
        this.errors = { errors: {} };
    }
}
