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 { DecimalPipe } from '@angular/common';
import { ActivatedRoute } 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 { Observable, Subscription } from 'rxjs';

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

@Component({
    selector: 'app-products',
    imports: [DecimalPipe, MatButtonModule, MatCardModule, MatDividerModule, MatIconModule, ListErrorsComponent],
    templateUrl: './products.component.html',
    styleUrl: './products.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 ProductsComponent 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 products: Array<Product> = [];
    public productsCount = 0;

    ngOnInit() {
        const data$: Observable<{ pageData: ProductsPageData }> = this.route.data as Observable<{
            pageData: ProductsPageData;
        }>;
        this._data = data$
            .pipe(takeUntilDestroyed(this.destroyRef))
            .subscribe((data: { pageData: ProductsPageData }) => {
                this.products = data.pageData.products;
                this.productsCount = data.pageData.count;
                //this.title = 'Fleurs CBD';
                this.title = data.pageData.products[0].productCategories[0]!.name;
                this.description = data.pageData.products[0].productCategories[0]!.description;
                this.titleService.setTitle(this.title);
                console.log(data.pageData);
                console.log(this.products);
            });
    }

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