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

// 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';

// Interfaces
import { CartData } from 'src/app/interfaces/user/cart-data';
import { environment } from 'src/environments/environment';
import { formatNumber } from '@angular/common';

@Component({
  standalone: false,
    selector: 'app-supplier-items-display',
    templateUrl: './supplier-items-display.component.html',
    styleUrls: ['./supplier-items-display.component.scss'],
})
export class SupplierItemsDisplayComponent implements OnInit, OnChanges {
    @Input() supplier!: CartData['data']['supplierData'];
    @Input() items!: CartData['data']['items'];
    @Input() isUserAllowed!: boolean;
    @Input() checkNotifyData!: boolean;

    @Output() emitcheckNotify = new EventEmitter<any>();
    @Output() emitchangeSupplier = new EventEmitter<any>();
    @Output() emitcheckQuantity = new EventEmitter<any>();
    @Output() emitkeypressQty = new EventEmitter<any>();
    @Output() emitremoveItem = new EventEmitter<any>();
    @Output() emitsetProductQty = new EventEmitter<any>();
    @Output() emitminPurchaseValidation = new EventEmitter<any>();
    @Output() messageKeyEmitter = new EventEmitter<any>();
    imgUrl: string = environment.imageUrl;
    oldQuantities: { [key: number]: number } = {}; // Store previous values per item

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

    /**
     * Remove icon tooltip configuration
     */
    removeTooltip = {
        title: 'Remove Item'
    };

    ngOnChanges(changes: SimpleChanges): void {
    }

    ngOnInit(): void {
        this.cartService.checkNotifyEmitter.subscribe((data) => {
            this.checkNotify(data.supplier, data.item)
        });
    }

    setOldQuantity(itemId: number, quantity: number) {
        this.oldQuantities[itemId] = quantity;
    }

    getOldQuantity(itemId: number): number {
        return this.oldQuantities[itemId];
    }

    /**
     * Checks if the cutoff time of the supplier has passed.
     * 
     * @param string timezoneId
     * @param string supplierCutOffTime
     * @returns Boolean
     */
    checkCutOff(supplierCutOffTime: any) {
        if (supplierCutOffTime !== '' && supplierCutOffTime !== undefined && supplierCutOffTime !== null) {
            var estOffset = this.cartService.getEstOffset();
            //Get the current time in milliseconds with regards to supplier's time zone
            var now = new Date();
            var d = new Date();
            var time = d.setHours(now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds()) + d.getTimezoneOffset() * 60 * 1000;
            var userConvertedTime = (time - estOffset);
            //Get the cut off time in milliseconds
            var supplierCutOff = this.cartService.getSupplierCutOffTimeObj(estOffset, supplierCutOffTime);
            var diff = 0;
            diff = Number(supplierCutOff) - Number(userConvertedTime);
            if (!(diff > 0)) {
                return true;
            }
        }
        return false;
    };

    /**
     * Check if a product notification is present and also set the supplier notice if necessary.
     * @param {type} item
     * @return {Boolean}
     */
    checkNotify(supplier: any, item: any) {
        var notifyFlag = false;
        supplier.accountUpdateRequired = false;
        if (supplier.supplierData.is_first_order) {
            let haveCrossedCreditLimit = (supplier.supplierData.first_order_credit_limit > 0 && supplier.supplierData.first_order_credit_limit < supplier.totalOrderAmount);
            let msgType = (supplier.supplierData.id === 113598) ? 'wasatchFirstOrder' : (haveCrossedCreditLimit ? 'firstOrdrCrdtLmtBlock' : 'firstOrder');
            this.cartValidationService.setValid(msgType, supplier, false);
            if (haveCrossedCreditLimit) {
                var msg = "Your 1st order with " + supplier.supplierData.name + " must be under the initial credit limit of $" + formatNumber(supplier.supplierData.first_order_credit_limit, 'en-US') + ", please adjust your order and then you can submit for Processing.";
                this.cartValidationService.setMsg(msgType, supplier, msg);
            }
        }
        if (item.is_refrigerated && supplier.shippingData["2day_refrg"]) {
            notifyFlag = true;
            this.cartValidationService.setValid('paragonRefrigeratedFound', supplier, false);
            // check regular refrigerated
        } else if (item.is_refrigerated) {
            notifyFlag = true;
            this.cartValidationService.setValid('refrigeratedFound', supplier, false);
        }
        //check if item is hazmat
        if (item.is_hazardous) {
            notifyFlag = true;
            this.cartValidationService.setValid('hazmatFound', supplier, false);
        }
        //check if out-of-stock
        if (item.sold_out || (item.item_available === false) || item.auction_expired || (item.avail_qty === 0)) {
            notifyFlag = true;
            this.cartValidationService.setValid('out-of-stock', supplier, false);
        }
        //check if item is Ground Shipping Only
        if (item.ground_shipping_only) {
            notifyFlag = true;
            this.cartValidationService.setValid('groundShippingOnly', supplier, false);
        }
        //check if item is Expired
        if (item.item_expired) {
            notifyFlag = true;
            this.cartValidationService.setValid('item-expired', supplier, false);
        }
        supplier.applyNowFlag = false;
        supplier.accountStatus = item.account_status;
        // item.account_status === null means there is no relation between source and buyer
        if (supplier.supplierData.delay_new_account_results === 1 && (item.account_status === null || item.account_status == 13 || item.account_status == 28 || item.account_status == 29) 
            && (item.account_no === '' || item.account_no === null)) {
            notifyFlag = true;
            this.cartValidationService.setValid('applyNow', supplier, false);
            supplier.applyNowFlag = true;
        }
        supplier.isAccountPending = false;
        if (supplier.supplierData.delay_new_account_results === 1 && item.account_status !== null && item.account_status != 13 && item.account_status != 28 && item.account_status != 29 && (item.account_no === '' || item.account_no === null)) {
            supplier.isAccountPending = true;
        }
        // for universal supplier if account status is Update Payment Information or Updated Application Required
        if (supplier.supplierData.delay_new_account_results === 0 && (item.account_status == 28 || item.account_status == 29)) {
            notifyFlag = true;
            this.cartValidationService.setValid('updateRequired', supplier, false);
            supplier.applyNowFlag = true;
        }
        // This condition is added as per TRX-7646
        if (supplier.supplierData.delay_new_account_results === 0 && supplier.supplierData.is_payment_info_enabled === 0 && (item.account_status === 28 || item.account_status === 29)) {
            notifyFlag = true;
            this.cartValidationService.setValid('updateRequired', supplier, false);
            supplier.accountUpdateRequired = true;
        }
        var controlRatioMsg = '';
        var controlStatement = '';

        //check for any control
        if (item.dea_schedule < 6 && item.dea_schedule !== null) {
            this.cartValidationService.setValid('controlSubstanceFound', supplier, false);
            if (item.controls_ratio_settings !== '' && item.controls_ratio_settings !== 'NoRatio') {
                controlRatioMsg = 'By placing this order, you agree to the source\'s control ratio: ' +
                    item.controls_ratio_settings + ' ' +
                    supplier.supplierData.noncontrol_value + '/' +
                    supplier.supplierData.control_value + '.\n\n';
            }
            else if (item.controls_ratio_settings !== '' && item.controls_ratio_settings === 'NoRatio') {
                controlRatioMsg = 'By placing this order, you agree to the source\'s control ratio: ' +
                    item.controls_ratio_settings + '.\n\n';
            }
            if (item.control_policy_statement !== '') {
                controlStatement = 'Source\'s control substance policy statement: ' + item.control_policy_statement;
            }
            var controlMsg = controlRatioMsg + controlStatement;
            this.cartValidationService.setMsg('controlSubstanceFound', supplier, controlMsg);
            notifyFlag = true;
            if (parseInt(item.control_application_status) !== 15 && parseInt(item.require_cs_app) === 1) {
                this.cartValidationService.setValid('applyForControls', supplier, false);
                notifyFlag = true;            
            }
        }

        //check for schedule 2 subtances
        if (parseInt(item.dea_schedule) === 2) {
            this.cartValidationService.setValid('schedule2Substance', supplier, false);
            notifyFlag = true;
        }

        //check for product shortage
        if (item.quantity > item.avail_qty && item.avail_qty > 0) {
            notifyFlag = true;
            this.cartValidationService.setValid('productShortage', supplier, false);
        }

        //check for price change
        if (item.is_price_changed) {
            notifyFlag = true;
            this.cartValidationService.setValid('priceChange', supplier, false);
        }

        //Check for CutoffTime
        if (this.checkCutOff(supplier.shippingData.cutoff_time)) {
            this.cartValidationService.setValid('cutoffTime', supplier, false);
        }

        if (item.is_child_first_order) {
            notifyFlag = true;
        }

        if (supplier.supplierData.gcr.amount_to_meet > 0) {
            notifyFlag = true;
            this.cartValidationService.setValid('gcrNotMet', supplier, false);
        }
        if (!supplier.supplierData.is_source_active) {
            notifyFlag = true;
            this.cartValidationService.setValid('suspendedSource', supplier, false);
        }
        if (supplier.supplierData.failed_orders_exists) {
            notifyFlag = true;
            this.cartValidationService.setValid('PrepayCreditCard', supplier, false);
        }
        return notifyFlag;
    };

    /**
     * Function called to display change supplier modal when icon is clicked
     */
    changeSupplier(currentItem: any, supplier: any) {
        const dataToEmit = {
            currentItem: currentItem,
            supplier: supplier
        }
        this.emitchangeSupplier.emit(dataToEmit)
    };

    //Disable if its a non-ndc
    checkDisableIcon(item: any) {
        var ndcCheck = this.cartValidationService.validateNdc(item);

        if ((item.ndc && ndcCheck) || (item.strength && item.dosage_form && ndcCheck)) {
            return true;
        }
        else {
            return false;
        }
    };

    checkQuantity(event: any) {
        this.emitcheckQuantity.emit(event);
    };

    isValueNaN(value: any): boolean {
        return isNaN(value);
    }

    /**
     * Allows only integer values and values greater than 1.
     * @param {type} event
     * @return {null}
     */
    keypressQty(event: any) {
        this.emitkeypressQty.emit(event);
    };

    /**
     * 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;
        }
    };

    minPurchaseValidation(quantity: number, minPurchaseQuantity: number, itemId: string, supplier: any) {
        const dataToEmit = {
            quantity: quantity,
            minPurchaseQuantity: minPurchaseQuantity,
            itemId: itemId,
            supplier: supplier
        }
        this.emitminPurchaseValidation.emit(dataToEmit)
    }

    setProductQty(auctionId: any, supplier: any, qty: any, oldValue: any, fromPage: any, minPurchaseQuantity: any) {
        const dataToEmit = {
            auctionId: auctionId,
            supplier: supplier,
            qty: qty,
            oldValue: oldValue,
            fromPage: fromPage,
            minPurchaseQuantity: minPurchaseQuantity
        }
        this.emitsetProductQty.emit(dataToEmit)
    }

    removeItem(auctionId: any, suppId: any, childSuppId: any) {
        const dataToEmit = {
            auctionId: auctionId,
            suppId: suppId,
            childSuppId: childSuppId
        }
        this.emitremoveItem.emit(dataToEmit)
    }
    
    /**
     * 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);
    }

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

}
