// Angular Core
import { Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, ChangeDetectionStrategy } from '@angular/core';
import { Subscription } from 'rxjs';

// Services
import { CartService } from 'src/app/services/cart/cart.service';
import { CartValidationService } from 'src/app/services/cartValidation/cart-validation.service';
import { DataTransmitterService } from 'src/app/services/dataTransmitter/data-transmitter.service';
import { SearchService } from 'src/app/services/search/search.service';
import { UtilitiesService } from 'src/app/services/utilities/utilities.service';
import { environment } from 'src/environments/environment';

// Components
import { LoadingmodalComponent } from 'src/app/components/loadingmodal/loadingmodal.component';
import { WrittenmodalComponent } from 'src/app/components/writtenmodal/writtenmodal.component';
// Interfaces
import { ModalConfig } from 'src/app/interfaces/common-interfaces';

// Third Party
import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import HelloSign from 'hellosign-embedded';
import { AlmostThereComponent } from 'src/app/components/cart/place-order-popup/almost-there/almost-there.component';

@Component({
  standalone: false,
  selector: 'app-supplier-items-footer',
  templateUrl: './supplier-items-footer.component.html',
  styleUrls: ['./supplier-items-footer.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SupplierItemsFooterComponent implements OnInit, OnDestroy {
  @Input() supplier!: any;
  @Input() isUserAllowed!: boolean;
  @Input() buyNowFlag!: boolean;
  @Input() messageKey!: string;
  @Input() isPreviewMode!: boolean;
  @Input() isAwaitingValidation!: boolean;
  @Output() setFlag = new EventEmitter<any>();
  @Output() emitplaceOrderNow = new EventEmitter<any>();
  @Output() emitremoveAll = new EventEmitter<any>();
  @Output() emitRefreshCart = new EventEmitter<any>();
  supplierTotal!: number
  imgUrl: string = environment.imageUrl;
  sitename!: string;
  sitenameListener!: Subscription;
  writtenModal!:NgbModalRef;
  writtenModalOpened!:boolean;

  constructor(
    private cartValidationService: CartValidationService,
    private cartService: CartService,
    private modalService: NgbModal,
    private searchService:SearchService,
    private dataTransmitter: DataTransmitterService,
    private utilities: UtilitiesService
  ) { }

  hellosign = {
      url: '',
      client_id: '',
      message: ''
  };

  accountStatuses!: any;

  ngOnDestroy(): void {
    this.sitenameListener.unsubscribe();
  }

  ngOnInit(): void {
    this.accountStatuses = this.utilities.getAccountStatuses()
    this.sitenameListener = this.dataTransmitter.sitename.subscribe((sitename) => {
      this.sitename = sitename;
    });
  }
  
    /*
    * Private Property for base modal config for almostThereModalConfig
    */
    almostThereModalConfig:ModalConfig = {
     showHeader: false,
     title: ""
    };
    
    almostThereModalSub!:NgbModalRef;
    displayAlmostThereModal() {
      this.almostThereModalConfig.title = "";
      this.almostThereModalSub = this.modalService.open(AlmostThereComponent, {size: 'sm'});
      this.almostThereModalSub.componentInstance.almostThereModalClose = () => {
        this.almostThereModalClose();
      };
    };

    /*
     * Method to close almostThere Modal
    */
    almostThereModalClose() {
       this.almostThereModalSub.close('ok');
    };
  /**
   * function to check if supplier qualifies for trxade credits
   * @returns {boolean}
   */
  displayIfCreditsExist(supplier: any) {
    var trxadeCredits = this.cartValidationService.checkIfCreditsExist(supplier);
    var credits = 0;
    if(supplier.qualifiedForCredit === true && trxadeCredits === true) {
      credits++;
    }
    if(credits > 0) {
        return true;
    }
    else {
        return false;
    }
  };

  /**
   * Calculating Trxade total for each supplier
   * @param {type} supplier
   */
  trxadeCreditsTotal(supplier: any) {
    var supplierTrxadeTotal = 0;
    var data: any =  Object.keys(supplier.items).map(key => ({key, value: data[key]}));

    data.forEach((item: any) => {
      supplierTrxadeTotal += item.value.credit_amount;
    })

    return supplierTrxadeTotal;
  };

  /**
  * Alert flag to set the danger icon if shipping not selected while checkout
  * @param {type} data
  * @return {Boolean}
  */
  alertShipping(data: any) {
    var flag: boolean = false;
    data.forEach((m: any) => {
      if(m.valid === false && m.key === 'shippingSelected' ) {
        flag = true;
      }
    })
    return flag;
  };

  /**
  * Sets the shipping method as selected
  * @param {type} supplier
  * @param {type} method
  * @return {undefined}
  */
  setSelected(supplier: any, method: any) {
    this.setFlag.emit(supplier.shippingData.shipping_methods)
    if(method.status !== 'Minimum Not Met' && method.status !== 'Not Available' && !supplier.supplierData.isDropShipEnabled) {
      method.selected = true;
      supplier.shippingData.selectedShipping = method.name;
      if(method.status === 'Not Met') {
          supplier.shippingData.shippingFee = method.feeForMinOrder;
      }
      else if(method.status === 'Minimum Met') {
          supplier.shippingData.shippingFee = 0;
      }
      // if supplier is trxade prime member gets products, grouped by estimation time
      if (supplier.supplierData.is_prime_supplier) {
          this.cartService.getETADLVRItems(supplier,method.name);
      }
      this.cartValidationService.validateShipping(supplier);
    }
  };

  placeOrderNow(supplier: any) {
    this.emitplaceOrderNow.emit(supplier)
  }

  checkControlsUnitRatio(supplier: any) {
    if(supplier.supplierData.controls_ratio_settings === 'UnitRatio' || 
        (supplier.supplierData.controls_ratio_settings === 'CustomRatio' && supplier.supplierData.units === 1)) {
            return true;
    }
    else {
        return false;
    }
  }
  checkControlsAmountRatio(supplier: any) {
    if(supplier.supplierData.controls_ratio_settings === 'AmountRatio' || 
        (supplier.supplierData.controls_ratio_settings === 'CustomRatio' && supplier.supplierData.units === 2)) {
            return true;
    }
    else {
        return false;
    }
  }
  setTotals(supplier: any) {
    var fee = Number(supplier.shippingData.shippingFee);

    var iTotal = 0;
    const dataArray =  Object.keys(supplier.items).map(key => ({key, value: supplier.items[key]}));
    
    dataArray.forEach((obj: any) => {
      var formatted_total_price = obj.value.total_price.toString().split(",").join("")
      iTotal += Number(formatted_total_price);
    })

    this.supplierTotal = fee + iTotal;
    return this.supplierTotal;
  }

  sourceTotal(supplier: any): number{
    var iTotal = 0;
    const dataArray =  Object.keys(supplier.items).map(key => ({key, value: supplier.items[key]}));
    
    dataArray.forEach((obj: any) => {
      var formatted_total_price = obj.value?.total_price.toString().split(",").join("")
      iTotal += Number(formatted_total_price);
    })
    return iTotal
  }

  removeAll(supplier: any){
    this.emitremoveAll.emit(supplier)
  }

  trackByFn(index: any, item: any): any{
    return item.key
  }

    /**
     * 
     * @param int supplierId
     * @param string signatureType
     * @returns void
    */
    loadingPopup!: NgbModalRef;
    cartApplyNow(supplierId: number, signatureType: string): void
    {
        let args = {
           'supplier_id': supplierId,
           'document_name': 'SupplierDocument',
           'method' : 'applyNow'
       };
       this.loadingPopup = this.modalService.open(LoadingmodalComponent, {size: 'sm'});
       if (signatureType === "WRITTEN") {
           this.sendCreditApp(args);
       } else {
           this.getHSForm(args);
       }
    }
    
    /**
    * Sends Supplier Credit Application document to Buyer
    * and displays "Check your Email" popup after email sent successfully to Buyers.
    *
    * @param array args
    *
    * @return void
    */
    fromCart: boolean = false;
    buyerEmail: string = "";
    sendCreditApp(args: {supplier_id: number, document_name: string, method: string}):void
    {
      var r = this.searchService.callDocument(args)
      .subscribe({
        next: (response) => {
          if(response.data.buyerEmail && args.method !== undefined) {
              var row :{supplierName: string, buyerEmail: string} = {
                supplierName : response.data.supplierName,
                buyerEmail : response.data.buyerEmail
              };
              this.fromCart = true;
              this.buyerEmail = response.data.buyerEmail;
              this.loadingPopup.close();
              this.writtenModal = this.modalService.open(WrittenmodalComponent, {size: 'sm'})
              this.writtenModal.componentInstance.row = row;
              this.writtenModal.componentInstance.title = "CHECK YOUR EMAIL";
              this.writtenModal.componentInstance.writtenModal = this.writtenModal;
              this.writtenModal.componentInstance.writtenClickOk = this.writtenClickOk;
              this.writtenModal.shown.subscribe(() => {
                this.writtenModalOpened = true;
                 this.updateAccountStatus(args);
              })
        
              this.writtenModal.closed.subscribe(() => {
                  this.writtenModalOpened = false;
              })
          }
        },
        error: (err) => {
          this.searchService.errorCallBack(err);
        },
        complete: () => { },
      })
    }

    /**
     * Close the written application modal
     * @return {undefined}
     */
    writtenClickOk() {
      this.writtenModal.close('ok');
    };

    /*
     * Method to update account status
     * @param int supplierId
     * @return void
    */
    updateEsignSubscribe!: Subscription;
    updateAccountStatus(args: {supplier_id: number, method: string}): void
    {
        if (args.method === "applyNow") {
            var params = {
               'supplier_id': args.supplier_id,
               'action': "process",
               'type': "CreditDocument"
            };
            this.updateEsignSubscribe = this.searchService.updateEsign(params)
            .subscribe({
                    next: (response) => {
                        this.emitRefreshCart.emit(false);
                    },
              error: (err) => {
                this.searchService.errorCallBack(err);
              },
              complete: () => { },
            })
        }
    }

    /**
     * Get esign document.
     * @param {type} args
     * @return void
    */
    getHSForm(args: {supplier_id: number, document_name: string, method: string}): void
    {
         var r = this.searchService.callDocument(args)
        .subscribe({
          next: (response) => {
            this.loadingPopup.close();
            if (response.data.url && response.data.client_id) {
               this.hellosign.url = response.data.url;
               this.hellosign.client_id = response.data.client_id;
               const client = new HelloSign({
                  clientId: this.hellosign.client_id,
               });
               client.open(this.hellosign.url, {
                    allowCancel: true,
                    skipDomainVerification: true,
                    debug: true
               });

              client.on('sign', (data: any) => {
                this.updateAccountStatus(args);
              });

              client.on('close', () => {
              });
            }
        },
        error: (err) => {
          this.searchService.errorCallBack(err);
        },
        complete: () => { },
      })
    }
}
