// Angular Core
import { ChangeDetectorRef, Component, ElementRef, Input, OnInit, Output, ViewChild, ViewEncapsulation } from '@angular/core';

// RxJs
import { Subscription, catchError, throwError } from 'rxjs';

// Services
import { CartService } from 'src/app/services/cart/cart.service';
import { CartValidationService } from 'src/app/services/cartValidation/cart-validation.service';
import { UtilitiesService } from 'src/app/services/utilities/utilities.service';

// Third Party
import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { environment } from 'src/environments/environment';

@Component({
  standalone: false,
  selector: 'app-change-supplier',
  templateUrl: './change-supplier.component.html',
  styleUrls: ['./change-supplier.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class ChangeSupplierComponent implements OnInit {
  @Input() item: any;
  @Input() supplier: any;
  @Input() render: any;
  @Input() auctionId: any;
  @Input() shoppingCart: any;
  @Input() ndcSpecificChecked: any;
  @Input() changeSupplierPopup!: NgbModalRef;
  @Input() changeSupplierClickBack!: () => void;
  @Input() initValidationMsgs!: () => void;
  addToCartSubscribe!: Subscription;
  similarProductsSubscribe!: Subscription;
  imgUrl: string = environment.imageUrl;

  @ViewChild('quantityInput') quantityInput!: ElementRef

  constructor(
    private cartService : CartService,
    private cartValidationService: CartValidationService,
    private utilitiesService: UtilitiesService,
    private cdr: ChangeDetectorRef
  ) { }

  ngOnInit(): void {
    this.render.selectedCompareMenuItem.value = 'All Suppliers'
    this.updateChangeSupplierResults(this.item)
  }

  changeSupplierConfirm(similar_auction_id: any) {
    this.changeProductInCart(similar_auction_id);
    this.changeSupplierPopup.close('Change Supplier');
    setTimeout(() => {
      this.initValidationMsgs();
    }, 3500);
  };

  changeProductInCart(similar_auction_id: any) {
    var similar_product_qty!: number;
    var changeSupplierId!: number;

    this.render.other.forEach((item: any) => {
      if(parseInt(similar_auction_id) === item.auction_id) {
        similar_product_qty = item.qty_in_cart > item.quantity ? item.quantity : item.qty_in_cart;
        changeSupplierId = item.supplier_id;
      }
    })

    this.addToCartSubscribe = this.cartService.addToCart(similar_auction_id, changeSupplierId, similar_product_qty, 'ChangeSupplier')
      .pipe(
        catchError(() => {
          return throwError(() => new Error('ups sommething happend'));
        })
      )
      .subscribe({
        next: () => {
          setTimeout(() => {
            const dataArray = Object.keys(this.shoppingCart.data).map(key => ({key, value: this.shoppingCart.data[key]}));
            dataArray.forEach((supplier: any) => {
              const itemsData = Object.keys(supplier.value.items).map(key => ({key, value: supplier.value.items[key]}));
              itemsData.forEach((item: any) => {
                if(item.key === similar_auction_id) {
                  const dataToEmit = {
                    suppId: supplier.value.supplierData.id,
                    repull: true,
                    notifDisplay: true
                  }
                  this.cartService.changeSuppProductsEmitter.emit(dataToEmit)
                }
              })
              supplier.value.etaItems = this.cartService.groupETAItems(supplier.value.items);
            })
          }, 3500);
        },
        error: (err) => {
          this.cartService.errorCallBack(err);
        },
        complete: () => { },
      })
  };

  updateChangeSupplierResults(item: any) {
    
    this.cartService.resetChangeSupplierFilter('strength');
    this.cartService.resetChangeSupplierFilter('dosageForm');
    this.cartService.setChangeSupplierSearchTerm(item.ndc);
    if (typeof(item.strength) !== 'undefined' && item.strength !== '') {
        this.cartService.setChangeSupplierStrength(item.strength);
    }
    if (typeof(item.dosage_form) !== 'undefined' && item.dosage_form !== '') {
        this.cartService.setChangeSupplierDosage(item.dosage_form);
    }
    this.cartService.setChangeSupplierAuctionId(item.id);
    this.cartService.setChangeSupplierNdcSpecific(this.ndcSpecificChecked);
    if(this.render.selectedCompareMenuItem.value === 'Suppliers in Cart' ) {
        var data = this.shoppingCart.data;
        const dataArray = Object.keys(this.shoppingCart.data).map(key => ({key, value: this.shoppingCart.data[key]}));
        dataArray.forEach((supplier: any) => {
          this.cartService.setChangeSupplierSpecific(supplier.key);
        })
    }
    else if (this.render.selectedCompareMenuItem.value === 'All Suppliers') {
        this.cartService.resetChangeSupplierFilter('supplier');
    };

    this.similarProductsSubscribe = this.cartService.similarProducts()
      .pipe(
        catchError(() => {
          return throwError(() => new Error('ups sommething happend'));
        })
      )
      .subscribe({
        next: (res: any) => {
          var search_results = res.data.search_result;
          this.render.other = search_results.other[0].similar;
          this.render.current = search_results.other[0].current;
          this.render.shippingInfo = search_results.shippingInfo;
        },
        error: (err) => {
          this.cartService.errorCallBack(err);
        },
        complete: () => { },
      })
  };

  keypressQty(event: any) {
    var code = event.keyCode || event.charCode;
    if ((code > 47 && code < 58) || (code === 8 || event.which === 0 || event.which === 13)) {
        return code;
    } else {
        event.preventDefault();
    }
  };

  /**
  * Method to disable the change supplier button on modal
  * @type boolean
  */
  checkChangeSupplierDisabled(disableId: any) {
    return disableId === '';
  };

  updateQuantity(renderData: any){
    renderData.qty_in_cart = renderData.qty_in_cart > renderData.quantity ? renderData.quantity : renderData.qty_in_cart
  }

  checkPurchaseQuantity(qty: number, min_purchase_quantity:number){
    const dataToEmit = {
      qty: qty,
      min_purchase_quantity: min_purchase_quantity
    }
    this.cartService.checkPurchaseQuantityEmitter.emit(dataToEmit)
  }

    /**
     * Condition to show the notification bell popover
     * @param {type} supplier
     * @param {type} item
     * @return {Boolean}
     */
    checkForPopover(item: any) {
        if (item.is_refrigerated || item.is_hazardous || item.sold_out || (item.item_available === false)
            || (item.quantity > item.avail_qty) || parseInt(item.dea_schedule) === 2 || (item.special_price > 0)
            || item.ground_shipping_only || item.is_child_first_order || (item.avail_qty === 0)) {

            return true;
        }
        else {
            return false;
        }
    };
    
    /**
     * Method to check if the Expiration Date is below 90 days or not
     * @param {string} expirationDate
     * @return {Boolean}
     */
    isExpireIn90Days(expirationDate: string) {
        return this.utilitiesService.getExpireDateBelow90Days(expirationDate);
    }

}
