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

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

import { AddToCartAction } from '../../../shared/action/cart.action';
import { DeleteCompareAction, GetCompareAction } from '../../../shared/action/compare.action';
import { Breadcrumb } from '../../../shared/components/widgets/breadcrumb/breadcrumb';
import { NoData } from '../../../shared/components/widgets/no-data/no-data';
import { IBreadcrumb } from '../../../shared/interface/breadcrumb';
import { ICartAddOrUpdate } from '../../../shared/interface/cart.interface';
import { IProduct } from '../../../shared/interface/product.interface';
import { CurrencySymbolPipe } from '../../../shared/pipe/currency-symbol.pipe';
import { TitleCasePipe } from '../../../shared/pipe/title-case.pipe';
import { CompareService } from '../../../shared/services/compare.service';
import { CompareState } from '../../../shared/state/compare.state';

@Component({
  selector: 'app-compare',
  imports: [
    CommonModule,
    TranslateModule,
    CurrencySymbolPipe,
    TitleCasePipe,
    NgbModule,
    Breadcrumb,
    NoData,
  ],
  templateUrl: './compare.html',
  styleUrl: './compare.scss',
})
export class Compare {
  private store = inject(Store);
  public compareService = inject(CompareService);

  public breadcrumb: IBreadcrumb = {
    title: 'Compare',
    items: [{ label: 'Compare', active: true }],
  };

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

  compareItems$: Observable<IProduct[]> = inject(Store).select(CompareState.compareItems);

  constructor() {
    this.store.dispatch(new GetCompareAction());
  }

  moveToCart(product: IProduct) {
    if (product) {
      const params: ICartAddOrUpdate = {
        id: null,
        product_id: product?.id,
        product: product ? product : null,
        variation: null,
        variation_id: null,
        quantity: 1,
      };
      this.store.dispatch(new AddToCartAction(params)).subscribe({
        complete: () => {
          this.removeCompare(product.id);
        },
      });
    }
  }

  removeCompare(id: number) {
    this.store.dispatch(new DeleteCompareAction(id));
  }
}
