import { Title } from '@angular/platform-browser';
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 { DatePipe, DecimalPipe } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { MatCardModule } from '@angular/material/card';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { Observable, Subscription } from 'rxjs';

import { ListErrorsComponent } from '@components/shared';
import { Errors, Product, ProductPageData } from '@models';

@Component({
    selector: 'app-product',
    imports: [DatePipe, DecimalPipe, MatCardModule, MatDividerModule, MatIconModule, ListErrorsComponent],
    templateUrl: './product.component.html',
    styleUrl: './product.component.scss',
    animations: [
        trigger('flyInOut', [
            state('in', style({ transform: 'translateY(0)' })),
            transition('void => *', [style({ transform: 'translateY(-100%)' }), animate(200)]),
            transition('* => void', [style({ transform: 'translateY(100%)' }), animate(200)]),
        ]),
    ],
})
export class ProductComponent implements OnInit, OnDestroy {
    private route = inject(ActivatedRoute);
    private titleService = inject(Title);

    private _data: Subscription = new Subscription();
    public title = 'Ad Astra - Produit';
    public description = "Encore un peu de patience, notre shop sera mis en ligne d'ici peu.";
    public errors: Errors = { errors: {} };
    public destroyRef = inject(DestroyRef);
    public product: Product = {} as Product;

    ngOnInit() {
        const data$: Observable<{ pageData: ProductPageData }> = this.route.data as Observable<{
            pageData: ProductPageData;
        }>;
        this._data = data$
            .pipe(takeUntilDestroyed(this.destroyRef))
            .subscribe((data: { pageData: ProductPageData }) => {
                this.product = data.pageData.product;
                this.title = this.product.name;
                this.description = this.product.description;
                this.titleService.setTitle(this.product.name);
                console.log(this.product);
            });
    }

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

    getProductTags() {
        return this.product.tags;
    }
}
