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

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

import { NoData } from '../../../../shared/components/widgets/no-data/no-data';
import { ProductBox } from '../../../../shared/components/widgets/product-box/product-box';
import { SkeletonProductBox } from '../../../../shared/components/widgets/product-box/widgets/skeleton-product-box/skeleton-product-box';
import * as data from '../../../../shared/data/owl-carousel';
import { IProduct } from '../../../../shared/interface/product.interface';
import { IOption } from '../../../../shared/interface/theme-option.interface';
import { ProductService } from '../../../../shared/services/product.service';
import { ProductState } from '../../../../shared/state/product.state';
import { ThemeOptionState } from '../../../../shared/state/theme-option.state';

@Component({
  selector: 'app-theme-product',
  imports: [CommonModule, CarouselModule, SkeletonProductBox, ProductBox, NoData],
  templateUrl: './product.html',
  styleUrl: './product.scss',
})
export class Product {
  public productService = inject(ProductService);

  readonly style = input<string>('vertical');
  readonly productIds = input<number[]>([]);
  readonly boxClass = input<string>();
  readonly productStyle = input<string>('');
  readonly layout = input<string>();
  readonly sliderOption = input<OwlOptions>(data.productSlider);
  readonly slider = input<boolean>();
  readonly showItem = input<number>();

  public products: IProduct[] = [];

  public skeletonItems = Array.from({ length: 6 }, (_, index) => index);

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

  ngOnChanges() {
    const productIds = this.productIds();
    if (Array.isArray(productIds) && productIds.length) {
      this.product$.subscribe(products => {
        this.products = products.filter(product => this.productIds()?.includes(product.id));
      });
    }
  }

  ngOnInit() {
    this.themeOption$.subscribe(option => {
      if (
        option?.product?.product_box_border ||
        option?.product?.image_bg ||
        option?.product?.product_box_bg
      ) {
        this.sliderOption()['margin'] = 15;
      }
    });
  }
}
