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

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

import { AddToCartAction } from '../../../../../../shared/action/cart.action';
import { Button } from '../../../../../../shared/components/widgets/button/button';
import { VariantAttributes } from '../../../../../../shared/components/widgets/variant-attributes/variant-attributes';
import { ICart, ICartAddOrUpdate } from '../../../../../../shared/interface/cart.interface';
import { IProduct, IVariation } from '../../../../../../shared/interface/product.interface';
import { CurrencySymbolPipe } from '../../../../../../shared/pipe/currency-symbol.pipe';
import { CartState } from '../../../../../../shared/state/cart.state';

@Component({
  selector: 'app-sticky-checkout',
  imports: [CurrencySymbolPipe, TranslateModule, VariantAttributes, Button],
  templateUrl: './sticky-checkout.html',
  styleUrl: './sticky-checkout.scss',
})
export class StickyCheckout {
  private store = inject(Store);

  @Input() product: IProduct;

  cartItem$: Observable<ICart[]> = inject(Store).select(CartState.cartItems);

  public cartItem: ICart | null;
  public productQty: number = 1;
  public selectedVariation: IVariation | null;

  ngOnChanges(changes: SimpleChanges) {
    if (changes['product'] && changes['product'].currentValue) {
      this.product = changes['product']?.currentValue;
    }
    this.cartItem$.subscribe(items => {
      this.cartItem = items?.find(item => item?.product?.id == this.product.id)!;
    });
  }

  selectVariation(variation: IVariation) {
    this.selectedVariation = variation;
  }

  updateQuantity(qty: number) {
    if (1 > this.productQty + qty) return;
    this.productQty = this.productQty + qty;
  }

  addToCart(product: IProduct) {
    if (product) {
      const params: ICartAddOrUpdate = {
        id:
          this.cartItem &&
          this.selectedVariation &&
          this.cartItem?.variation &&
          this.selectedVariation?.id == this.cartItem?.variation?.id
            ? this.cartItem.id
            : null,
        product_id: product?.id!,
        product: product ? product : null,
        variation: this.selectedVariation ? this.selectedVariation : null,
        variation_id: this.selectedVariation?.id ? this.selectedVariation?.id : null,
        quantity: this.productQty,
      };
      this.store.dispatch(new AddToCartAction(params));
    }
  }

  externalProductLink(link: string) {
    if (link) {
      window.open(link, '_blank');
    }
  }
}
