import { CommonModule } from '@angular/common';
import { Component, inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { TranslatePipe } from '@ngx-translate/core';
import { Store } from '@ngxs/store';
import { Observable } from 'rxjs';

import { GetProductsAction } from '../../../shared/action/product.action';
import { Breadcrumb } from '../../../shared/components/widgets/breadcrumb/breadcrumb';
import { IAuthor } from '../../../shared/interface/author.interface';
import { IBreadcrumb } from '../../../shared/interface/breadcrumb';
import { Params } from '../../../shared/interface/core.interface';
import { IProductModel } from '../../../shared/interface/product.interface';
import { AuthorState } from '../../../shared/state/author.state';
import { ProductState } from '../../../shared/state/product.state';
import { CollectionProducts } from '../collection/widgets/collection-products/collection-products';

@Component({
  selector: 'app-author',
  imports: [CommonModule, Breadcrumb, CollectionProducts, TranslatePipe],
  templateUrl: './author.html',
  styleUrl: './author.scss',
})
export class Author {
  private store = inject(Store);
  private route = inject(ActivatedRoute);

  product$: Observable<IProductModel> = inject(Store).select(ProductState.product);
  author$: Observable<IAuthor> = inject(Store).select(
    AuthorState.selectedAuthor,
  ) as Observable<IAuthor>;

  public breadcrumb: IBreadcrumb = {
    title: 'Category',
    items: [{ label: '', active: false }],
  };
  public activeAuthor: string | null;
  public author: IAuthor;
  public filter: Params = {
    page: 1, // Current page number
    paginate: 40, // Display per page
    status: 1,
    field: 'created_at',
    price: '',
    category: '',
    tag: '',
    sort: 'asc', // ASC, DSC
    sortBy: 'asc',
    rating: '',
    attribute: '',
  };

  constructor() {
    if (this.route.snapshot.paramMap.get('slug')) {
      this.activeAuthor = this.route.snapshot.paramMap.get('slug');
    }
  }

  ngOnInit() {
    this.author$.subscribe(author => (this.author = author));
    this.breadcrumb.title = `IAuthor: ${this.author?.author_name}`;
    this.breadcrumb.items[0].label = this.author?.author_name;
    this.filter['author_id'] = this.author.id;
    this.store.dispatch(new GetProductsAction(this.filter));
  }
}
