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

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

import { environment } from '../../../../../../environments/environment';
import { AddToCartAction } from '../../../../../shared/action/cart.action';
import { AddToCompareAction } from '../../../../../shared/action/compare.action';
import {
  AddToWishlistAction,
  DeleteWishlistAction,
} from '../../../../../shared/action/wishlist.action';
import { ICart, ICartAddOrUpdate } from '../../../../../shared/interface/cart.interface';
import { IProduct, IVariation } from '../../../../../shared/interface/product.interface';
import { IOption } from '../../../../../shared/interface/theme-option.interface';
import { CartState } from '../../../../../shared/state/cart.state';
import { ProductContain } from '../widgets/product-contain/product-contain';
import { ProductDetailsTabs } from '../widgets/product-details-tabs/product-details-tabs';
import { ProductWholesale } from '../widgets/product-wholesale/product-wholesale';
import { VendorContain } from '../widgets/vendor-contain/vendor-contain';
import { VideoPlayModal } from '../widgets/video-play-modal/video-play-modal';

@Component({
  selector: 'app-product-digital',
  imports: [
    TranslateModule,
    CommonModule,
    ProductDetailsTabs,
    VendorContain,
    ProductContain,
    ProductWholesale,
    VideoPlayModal,
  ],
  templateUrl: './product-digital.html',
  styleUrl: './product-digital.scss',
})
export class ProductDigital {
  private store = inject(Store);
  private router = inject(Router);

  @Input() product: IProduct;
  readonly option = input<IOption | null>();

  readonly VideoPlayModal = viewChild<VideoPlayModal>('videoPlayModal');

  public productQty: number = 1;
  public selectedVariation: IVariation | null;
  public totalPrice: number = 0;
  public cartItem: ICart | null;
  public url: string = environment.baseURL;

  public videType: string[] = ['video/mp4', 'video/webm', 'video/ogg'];
  public audioType: string[] = ['audio/mpeg', 'audio/wav', 'audio/ogg'];

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

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

  addToWishlist(product: IProduct) {
    product['is_wishlist'] = !product['is_wishlist'];
    let action = product['is_wishlist']
      ? new AddToWishlistAction({ product_id: product.id })
      : new DeleteWishlistAction(product.id);
    if (action) {
      this.store.dispatch(action);
    }
  }

  addToCompare(id: number) {
    this.store.dispatch(new AddToCompareAction({ product_id: id }));
  }

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

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

  wholesalePriceCal() {
    let wholesale =
      this.product.wholesales.find(
        value => value.min_qty <= this.productQty && value.max_qty >= this.productQty,
      ) || null;
    if (wholesale && this.product.wholesale_price_type == 'fixed') {
      this.totalPrice = this.productQty * wholesale.value;
    } else if (wholesale && this.product.wholesale_price_type == 'percentage') {
      this.totalPrice =
        this.productQty *
        (this.selectedVariation ? this.selectedVariation.sale_price : this.product.sale_price);
      this.totalPrice = this.totalPrice - this.totalPrice * (wholesale.value / 100);
    } else {
      this.totalPrice =
        this.productQty *
        (this.selectedVariation ? this.selectedVariation.sale_price : this.product.sale_price);
    }
  }

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

  addToCart(product: IProduct, buyNow?: boolean) {
    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)).subscribe({
        complete: () => {
          if (buyNow) {
            void this.router.navigate(['/checkout']);
          }
        },
      });
    }
  }

  shareOnFacebook(slug: string) {
    const facebookShareUrl = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(this.url + '/product/' + slug)}`;
    window.open(facebookShareUrl, '_blank');
  }

  shareOnInstagram(slug: string) {
    const whatsappShareUrl = `https://api.instagram.com/send?text=${encodeURIComponent(this.url + '/product/' + slug)}`;
    window.open(whatsappShareUrl, '_blank');
  }

  shareOnWhatsApp(slug: string) {
    const whatsappShareUrl = `https://api.whatsapp.com/send?text=${encodeURIComponent(this.url + '/product/' + slug)}`;
    window.open(whatsappShareUrl, '_blank');
  }
}
