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

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

import { AddToCartAction } from '../../../../../action/cart.action';
import { ICart, ICartAddOrUpdate } from '../../../../../interface/cart.interface';
import { IProduct } from '../../../../../interface/product.interface';
import { CartState } from '../../../../../state/cart.state';
import { Button } from '../../../button/button';
import { ProductDetailModal } from '../../../modal/product-detail-modal/product-detail-modal';
import { VariationModal } from '../../../modal/variation-modal/variation-modal';

@Component({
  selector: 'app-product-cart-button',
  imports: [TranslateModule, Button, ProductDetailModal, VariationModal],
  templateUrl: './product-cart-button.html',
  styleUrl: './product-cart-button.scss',
})
export class ProductCartButton {
  private store = inject(Store);
  @Input() product: IProduct;
  readonly text = input<string>();
  @Input() iconClass: string;

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

  readonly productDetailModal = viewChild<ProductDetailModal>('productDetailModal');

  public cartItem: ICart | null;
  public currentDate: number | null;
  public saleStartDate: number | null;

  ngOnInit() {
    this.cartItem$.subscribe(items => {
      this.cartItem = items?.find(item => item?.product?.id == this.product.id)!;
    });
  }

  addToCart(product: IProduct, qty: number) {
    console.warn('🚀 ~ ProductCartButtonComponent ~ addToCart ~ product:', product);
    const params: ICartAddOrUpdate = {
      id: this.cartItem ? this.cartItem.id : null,
      product: product,
      product_id: product?.id,
      variation_id: this.cartItem ? this.cartItem?.variation_id : null,
      variation: this.cartItem ? this.cartItem?.variation : null,
      quantity: qty,
    };
    this.store.dispatch(new AddToCartAction(params));
  }

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