// Angular Core
import { Component, Input, OnInit } from '@angular/core';

// Components
import { CartratioComponent } from '../cartratio/cartratio.component';

// Services
import { CartService } from '../../../../services/cart/cart.service';

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

@Component({
  standalone: false,
  selector: 'app-shownotificationacceptance',
  templateUrl: './shownotificationacceptance.component.html',
  styleUrls: ['./shownotificationacceptance.component.scss']
})
export class ShownotificationacceptanceComponent implements OnInit {
  @Input() suppliers!: any
  @Input() checkoutBlockedMsgs!: any
  @Input() showNotificationAcceptancePopup!: NgbModalRef;
  @Input() checkShippingFeeChange!: (supplierInfo: any) => boolean;
  // @Input() checkoutClickOk!: (suppliers: any) => void;
  @Input() checkDisabled!: boolean;
  imgUrl: string = environment.imageUrl;

  constructor(
    private modalService: NgbModal,
    private cartService : CartService,
  ) { }

  ngOnInit(): void {
  }

checkoutClickNo(suppliers: any, supplierIndex: any) {
    const dataArray = Object.values(suppliers);  // Use Object.values() to retain supplier structure
    const checkShipFeeChange = this.checkShippingFeeChange(suppliers);
    
    let controlsMet = 0;
    
    dataArray.forEach((supplier: any) => {
        if (!supplier.supplierData?.isMet && supplier?.supplierData?.showRatio) {  
            controlsMet++;
        }
    });
    if (controlsMet > 0) {
        this.showControlsRatioModal();
    }

    if (checkShipFeeChange) {
        this.cartService.showCartRefreshEmitter.emit();
    }

    this.showNotificationAcceptancePopup.dismiss('No, return to cart');

    // TRX-7753 - Scroll to the supplier index if it exists
    if (supplierIndex) {
        const scrollDiv = document.getElementById(supplierIndex);
        if (scrollDiv) {
            scrollDiv.scrollIntoView();
        }
    }
}

  checkoutClickOk(suppliers: any){
    this.cartService.checkoutClick.emit(suppliers)
  }

  cartRatioPopup!: NgbModalRef
  showControlsRatioModal(){
    this.cartRatioPopup = this.modalService.open(CartratioComponent, {size: 'sm'});
    this.cartRatioPopup.componentInstance.cartRatioPopup = this.cartRatioPopup
    this.cartRatioPopup.componentInstance.clickControlsRatioOkay = this.clickControlsRatioOkay
  }

  clickControlsRatioOkay(){
    this.cartRatioPopup.close("Okay")
    this.showNotificationAcceptancePopup.close("Okay")
  }

}