import { Component, SimpleChanges, inject, input, viewChild } from '@angular/core';

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

import { GetDealProductsAction } from '../../../../../shared/action/product.action';
import { IProduct } from '../../../../../shared/interface/product.interface';
import { IOption } from '../../../../../shared/interface/theme-option.interface';
import { ProductState } from '../../../../../shared/state/product.state';
import { Button } from '../../../widgets/button/button';
import { DealsModal } from '../../../widgets/modal/deals-modal/deals-modal';

@Component({
  selector: 'app-deal',
  imports: [TranslateModule, Button, DealsModal],
  templateUrl: './deal.html',
  styleUrl: './deal.scss',
})
export class Deal {
  private store = inject(Store);

  readonly style = input<string>('basic');
  readonly data = input<IOption | null>();

  readonly DealsModal = viewChild<DealsModal>('dealsModal');

  dealProducts$: Observable<IProduct[]> = inject(Store).select(
    ProductState.dealProducts,
  ) as Observable<IProduct[]>;

  public dealProducts: IProduct[];
  public ids: number[];

  ngOnChanges(changes: SimpleChanges) {
    this.ids = changes['data']?.currentValue?.header?.today_deals;
  }

  ngOnInit() {
    if (Array.isArray(this.ids)) {
      this.store.dispatch(new GetDealProductsAction({ ids: this.ids?.join() }));
      this.dealProducts$.subscribe(product => {
        if (product) {
          this.dealProducts = product;
        }
      });
      // this.store.dispatch(new GetDealProductsAction({ids: this.ids?.join()})).subscribe({
      //   next: (val) => {
      //    this.dealProducts = val?.product?.dealProducts;
      //   }
      // });
    }
  }
}
