import { CommonModule } from '@angular/common';
import { Component, inject, Input, input } from '@angular/core';

import { Store } from '@ngxs/store';
import { OwlOptions } from 'ngx-owl-carousel-o';
import { Observable } from 'rxjs';

import { ProductBox } from '../../../../shared/components/widgets/product-box/product-box';
import { Title } from '../../../../shared/components/widgets/title/title';
import { IProduct } from '../../../../shared/interface/product.interface';
import { IOption } from '../../../../shared/interface/theme-option.interface';
import { ThemeOptionService } from '../../../../shared/services/theme-option.service';
import { ProductState } from '../../../../shared/state/product.state';
import { ThemeOptionState } from '../../../../shared/state/theme-option.state';
import { ThemeCategories } from '../categories/categories';

@Component({
  selector: 'app-category-product-filter',
  imports: [CommonModule, Title, ThemeCategories, ProductBox],
  templateUrl: './category-product-filter.html',
  styleUrl: './category-product-filter.scss',
})
export class CategoryProductFilter {
  public themeOptionService = inject(ThemeOptionService);
  private store = inject(Store);

  @Input() data: any;
  readonly sliderOption = input<OwlOptions>();
  readonly grid = input<number>(3);

  themeOption$: Observable<IOption> = inject(Store).select(
    ThemeOptionState.themeOptions,
  ) as Observable<IOption>;
  categoryProduct$: Observable<IProduct[]> = inject(Store).select(
    ProductState.categoryProducts,
  ) as Observable<IProduct[]>;

  public products: IProduct[];
  public selectedCategoryId: number;
  public productFilterIds: number[] = [];

  ngOnChanges() {
    this.categoryProduct$.subscribe(products => {
      this.products = products.map(product => product).slice(0, this.grid() * 2);
    });
  }

  selectCategory(id: number) {
    this.selectedCategoryId = id;
    this.categoryProduct$.subscribe(products => {
      if (id) {
        this.products = products
          .filter(product => product?.categories?.map(category => category.id).includes(id))
          .map(product => product)
          .slice(0, this.grid() * 2);
      } else {
        this.products = products
          .filter(product => product?.categories?.map(category => category.id))
          .map(product => product)
          .slice(0, this.grid() * 2);
      }
    });
  }
}
