import { Component, Input, inject, input, output } from '@angular/core';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';

import { TranslateModule } from '@ngx-translate/core';
import { Store } from '@ngxs/store';
import { CarouselModule, OwlOptions } from 'ngx-owl-carousel-o';
import { Observable } from 'rxjs';

import { ICategory, ICategoryModel } from '../../../interface/category.interface';
import { AttributeService } from '../../../services/attribute.service';
import { CategoryState } from '../../../state/category.state';
import { Button } from '../button/button';
import { NoData } from '../no-data/no-data';

@Component({
  selector: 'app-categories',
  imports: [TranslateModule, RouterModule, CarouselModule, Button, NoData],
  templateUrl: './categories.html',
  styleUrl: './categories.scss',
})
export class Categories {
  private route = inject(ActivatedRoute);
  public attributeService = inject(AttributeService);
  private router = inject(Router);

  category$: Observable<ICategoryModel> = inject(Store).select(CategoryState.category);

  readonly categoryIds = input<number[]>([]);
  readonly style = input<string>('vertical');
  @Input() title?: string;
  @Input() image?: string;
  readonly theme = input<string>();
  readonly sliderOption = input<OwlOptions>();
  readonly selectedCategoryId = input<number>();
  readonly bgImage = input<string>();

  readonly selectedCategory = output<number>();

  public categories: ICategory[];
  public selectedCategorySlug: string[] = [];

  constructor() {
    this.route.queryParams.subscribe(params => {
      this.selectedCategorySlug = params['category'] ? params['category'].split(',') : [];
    });

    this.category$.subscribe(res => (this.categories = res.data.map(category => category)));
  }

  ngOnChanges() {
    const categoryIds = this.categoryIds();
    if (categoryIds && categoryIds.length) {
      this.category$.subscribe(
        res =>
          (this.categories = res.data.filter(category =>
            this.categoryIds()?.includes(category.id),
          )),
      );
    }
  }

  selectCategory(id?: number) {
    this.selectedCategory.emit(id!);
  }

  redirectToCollection(slug: string) {
    let index = this.selectedCategorySlug.indexOf(slug);
    if (index === -1) this.selectedCategorySlug.push(slug);
    else this.selectedCategorySlug.splice(index, 1);

    void this.router.navigate(['/collections'], {
      relativeTo: this.route,
      queryParams: {
        category: this.selectedCategorySlug.length ? this.selectedCategorySlug?.join(',') : null,
      },
      queryParamsHandling: 'merge', // preserve the existing query params in the route
      skipLocationChange: false, // do trigger navigation
    });
  }

  closeCanvasMenu() {
    this.attributeService.offCanvasMenu = false;
  }
}
