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

import { Store } from '@ngxs/store';
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 { ProductState } from '../../../../../../shared/state/product.state';
import { ThemeOptionState } from '../../../../../../shared/state/theme-option.state';

@Component({
  selector: 'app-related-products',
  imports: [CommonModule, Title, ProductBox],
  templateUrl: './related-products.html',
  styleUrl: './related-products.scss',
})
export class RelatedProducts {
  relatedProduct$: Observable<IProduct[]> = inject(Store).select(ProductState.relatedProducts);
  themeOption$: Observable<IOption> = inject(Store).select(
    ThemeOptionState.themeOptions,
  ) as Observable<IOption>;

  readonly product = input<IProduct | null>();

  public relatedProducts: IProduct[] = [];

  ngOnChanges() {
    const productValue = this.product();
    if (productValue?.related_products && Array.isArray(productValue?.related_products)) {
      this.relatedProduct$.subscribe(products => {
        this.relatedProducts = products.filter(product =>
          this.product()?.related_products?.includes(product?.id),
        );
      });
    }
  }
}
