import {tiObj} from "./generic.js"
import {} from "./pdp-generic.js"
import {} from "./calculator.js"
import {goToStep3, resetInvalidMsg} from "./installation.js"

let radioSuccessCount,
    removalValueCheck;
const step2Next = $('.ti__step2 .ti__next .btn'),
    step3Next = $('.ti__step3 .ti__next .btn'),
    removalRadio = $('.ti__cost_removal-radio input'),
    removalExisting = $('.ti__cost_removal-existing'),
    step3Radio = $('.fi__step3-choose input'),
    levelingRadio = $('.ti__cost-leveling > .ti__cost_removal-radio input'),
    levelingBlock = $('.ti__cost-leveling'),
    additionalLevelingRadio = $('.ti__cost_removal-leveling'),
    thresholdRadio = $('.ti__cost-threshold > .ti__cost_removal-radio input'),
    tiCostThresholdStr = '.ti__cost-threshold',
    scotiaRadio = $('.ti__cost-scotia > .ti__cost_removal-radio input'),
    underlayRadio = $('.ti__cost-underlay > .ti__cost_removal-radio input'),
    tiCostRemovalRadioStr = '.ti__cost_removal-radio',
    cardInput = $('.complem__input'),
    cardSumValueStr = '.complem__sum-value',
    addButton = $('.complem__action button'),
    removeComplement = $('.ti__cost_removal-remove'),
    complementCardHeader = $('.complem__head'),
    complementCardList = '.complem__list',
    costRemovalStr = '.ti__cost_removal',
    complemStr = '.complem',
    complemTotalStr = '.complem__total',
    complemTotalErrorStr = 'complem__total-error',
    tiCostLevelingStr = '.ti__cost-leveling',
    tiCostPostCodeStr = '.ti__cost_postcode',
    tiCostRemovalAdd = 'ti__cost_removal-add',
    tiCostRemovalCalc = 'ti__cost_removal-calc',
    tiCostTrimmingStr = 'ti__cost-trimming',
    tiCostRemovalYes = 'ti__cost_removal-yes',
    tiCostInvalidStr = 'ti__cost-invalid',
    tiCostInvalidStr2 = 'ti__cost-invalid-2',
    tiCostRemovalInput = '.ti__cost_removal-input input',
    tiCostInputInvalid = 'ti__cost_input-invalid',
    complemHeadStr = '.complem__head',
    tiCostRemovalProductStr = '.ti__cost_removal-product',
    tiCostRemovalValueStr = '.ti__cost_removal-value',
    complemPriceValueStr = '.complem__price-value',
    tiChooseFirstPurch = 'ti__choose_first-purch',
    tiChooseFirstOnly = 'ti__choose_first-only',
    tiChooseFirstStr = '.ti__choose_first',
    formDetailsOpenStr = 'form-details_open',
    innerRow = $('.form-details .form-row');

removeComplement.on('click', function (e) {
    e.preventDefault();
    let block = $(this).closest(costRemovalStr);
    block.removeClass(tiCostRemovalAdd);
    block.addClass(tiCostRemovalYes);
});

addButton.on('click', function () {
    let card = $(this).closest(complemStr);
    let block = card.closest(costRemovalStr);
    let name = card.find(complemHeadStr).text();
    let sum = card.find(cardSumValueStr).text();

    resetInvalidMsg(this);

    block.find(tiCostRemovalProductStr).text(name);
    block.find(tiCostRemovalValueStr).text(sum);

    block.removeClass(tiCostRemovalYes);
    block.addClass(tiCostRemovalAdd);
});

cardInput.on('input', function () {
    let count = parseInt($(this).find('input').val());
    let card = $(this).closest(complemStr);
    let price = card.find(complemPriceValueStr).text();
    let totalPrice;

    if (count < 1 || count >= 99 || isNaN(count)) {
        totalPrice = 0;
        card.find(complemTotalStr).addClass(complemTotalErrorStr);
    } else {
        totalPrice = price * count;
        card.find(complemTotalStr).removeClass(complemTotalErrorStr);
    }

    card.find(cardSumValueStr).text(totalPrice);
});

levelingRadio.change(function () {
    resetInvalidMsg(this);
    if ($(this).siblings('span').text() === 'Yes') {
        $(levelingBlock).addClass(tiCostRemovalYes);
        radioSuccessCount = 7;
    } else {
        $(levelingBlock).removeClass(tiCostRemovalYes);
        radioSuccessCount = 6;
    }
});

removalExisting.children(tiCostRemovalRadioStr)
    .find('input').on('change', function () {
    if ($(this).attr('id') === '0_removal-exist-yes-lam_'
        || $(this).attr('id') === '1_removal-exist-yes-tile_') {
        removalExisting.addClass(tiCostRemovalCalc);
        removalValueCheck = false;
    } else {
        removalExisting.removeClass(tiCostRemovalCalc);
        removalExisting.removeClass(tiCostInputInvalid);
        removalValueCheck = true;
    }
});

removalExisting.find(tiCostRemovalInput)
    .on('input', function () {
        if ($(this).val() > 0) {
            removalExisting.removeClass(tiCostInputInvalid);
        }
    });

$(thresholdRadio).change(showComplementCards);
$(scotiaRadio).change(showComplementCards);
$(underlayRadio).change(showComplementCards);

removalRadio.change(function () {
    resetInvalidMsg(this);

    let radioGroup = $(this).closest(tiCostRemovalRadioStr).find('input');
    radioGroup.map(function () {
        $(this).removeAttr('checked');
    });
    $(this).attr('checked', 'checked');
});

step2Next.on('click', function () {

    let postCodeValue = $(tiCostPostCodeStr).find('input').val();
    let radioCount = 0;
    let noComplementBlock = true;
    let noTrimmingBlock = true;
    let noTrimmingCheck = false;

    let postCodeBlock = $(tiCostPostCodeStr);
    let radioBlock = $(costRemovalStr);

    if (removalExisting.hasClass(tiCostRemovalCalc)) {
        if ($(tiCostRemovalInput).val() > 0) {
            removalExisting.removeClass(tiCostInputInvalid);
            removalValueCheck = true;
        } else {
            removalExisting.addClass(tiCostInputInvalid);
            removalValueCheck = false;
        }
    }

    removalRadio.map(function () {
        if ($(this).attr('checked') === 'checked') {
            radioCount++;
        } else {
            $(this).closest(costRemovalStr).addClass(tiCostInvalidStr);
        }
        return radioCount;
    });

    if (radioBlock.not(tiCostLevelingStr).hasClass(tiCostRemovalYes)) {
        noComplementBlock = false;
    }

    if ($(tiCostThresholdStr).hasClass(tiCostTrimmingStr)) {

        $('.ti__cost_removal_second').find('input').is(function () {
            if ($(this).attr('checked') === 'checked') {
                noTrimmingCheck = true;
            }
        })
    } else {
        noTrimmingCheck = true;
    }

    if (postCodeValue.length > 4
        && radioCount >= radioSuccessCount
        && noComplementBlock
        && noTrimmingCheck
        && removalValueCheck) {
        if (tiObj.system.notification2) {
            tiObj.system.notification2.hide();
        }
        radioBlock.removeClass(tiCostInvalidStr);
        postCodeBlock.removeClass(tiCostInvalidStr);
        goToStep3();
    } else {
        tiObj.system.notification2 = Wick.Notification.show({
            text: 'Please answer the questions above before continuing.',
            container: $(this).parents('.ti__step').find('.ti__error'),
            type: 'error',
            noScrolling: true,
        });
        postCodeBlock.removeClass(tiCostInvalidStr);
        radioBlock.removeClass(tiCostInvalidStr);

        if (radioBlock.hasClass(tiCostTrimmingStr)) {
            $('.ti__cost-trimming').addClass(tiCostInvalidStr2);
        }

        radioBlock.map(function () {
            $(this).addClass(tiCostInvalidStr);

            $(this).find('input').map(function () {
                let attr = $(this).attr('checked');
                if (typeof attr !== typeof undefined && attr !== false) {
                    $(this).closest(costRemovalStr).removeClass(tiCostInvalidStr);
                }
            });

            if ($(this).hasClass(tiCostRemovalYes)) {
                $(this).addClass(tiCostInvalidStr);
            }
        });

        if (levelingBlock.hasClass(tiCostRemovalYes)) {
            $(this).closest('.fi').find(tiCostLevelingStr).addClass(tiCostInvalidStr);

            additionalLevelingRadio.find('input').map(function () {
                let attr = $(this).attr('checked');
                if (typeof attr !== typeof undefined && attr !== false) {
                    $(this).closest(tiCostLevelingStr).removeClass(tiCostInvalidStr);
                }
            })
        }

        if ($(tiCostThresholdStr).hasClass(tiCostTrimmingStr)) {
            $('.ti__cost_removal_second').find('input').is(function () {
                if ($(this).attr('checked') === 'checked') {
                    $(tiCostThresholdStr).removeClass(tiCostInvalidStr2);
                }
            })
        }
        if (!(postCodeValue.length > 4)) {
            postCodeBlock.addClass(tiCostInvalidStr);
        }
    }
});

step3Next.on('click', function () {
    let radioCount = 0;
    let radioValCount = 1;
    let block = $(this)
        .closest('.fi__step3-choose')
        .find(tiChooseFirstStr)
        .children('.ti__cost_options-list');
    let blockInput = block.children('label').find('input'),
        contactInfo = [];

    if ($(tiChooseFirstStr).hasClass(formDetailsOpenStr)) {
        innerRow.each(function () {
            if ($(this).find('input').val() === "") {
                $(this).find(".form-row__error").css("display", "block");
                $(this).find('input').css("border", "1px solid #cf000f");
                contactInfo.push(0)
            } else {
                $(this).find(".form-row__error").css("display", "none");
                $(this).find('input').css("border", "1px solid #ccc");
                contactInfo.push(1)
            }
        })
    }

    function checkContactInfo() {
        if ($(tiChooseFirstStr).hasClass(formDetailsOpenStr)) {
            return contactInfo.every((item) => item !== 0);
        } else {
            return true;
        }
    }

    let hasContactInfo = checkContactInfo();

    blockInput.map(function () {
        if ($(this).attr('checked') === 'checked') {
            radioCount++;
        }
        return radioCount;
    });

    if (radioCount >= radioValCount && hasContactInfo) {
        if (tiObj.system.notification2) {
            tiObj.system.notification2.hide();
        }

        if (tiObj.userInfo.finalChoose == 'Call me to discuss installation') {
            $('#modal-thank-you').modal();
        }
    } else {
        tiObj.system.notification2 = Wick.Notification.show({
            text: 'Please answer the questions above before continuing.',
            container: $(this).parents('.ti__step').find('.ti__error'),
            type: 'error',
            noScrolling: true,
        });
    }
});

step3Radio.change(function () {
    let radioGroup = $(this).closest('.ti__cost_options-list'),
        inputs = radioGroup.children('label').find('input');

    inputs.map(function () {
        $(this).removeAttr('checked');
    });
    $(this).attr('checked', 'checked');

    if (radioGroup.parent().hasClass('ti__choose_first')) {
        let parentBlock = $(this).closest(tiChooseFirstStr);
        let sumBlock = parentBlock.closest('.ti__choose').find('.ti__overview-price');
        parentBlock.removeClass(tiChooseFirstPurch);
        parentBlock.removeClass(tiChooseFirstOnly);
        parentBlock.removeClass(formDetailsOpenStr);
        sumBlock.removeClass('ti__overview-price_only');

        if ($(this).attr('id') === '_purchase_') {
            parentBlock.addClass(tiChooseFirstPurch)
        } else if ($(this).attr('id') === '_purchase-only_') {
            parentBlock.addClass(tiChooseFirstOnly);
            sumBlock.addClass('ti__overview-price_only')
        } else if ($(this).attr('id') === '_call-me_') {
            parentBlock.addClass(formDetailsOpenStr);
            tiObj.userInfo.finalChoose = $(this).siblings('span').text();
        }
    }
});

function showComplementCards() {
    let context = $(this).closest(costRemovalStr);

    if ($(this).siblings('span').text() === 'Yes') {
        if (context.hasClass('ti__cost-threshold')) {
            context.addClass(tiCostTrimmingStr);
        } else {
            context.removeClass(tiCostTrimmingStr);
        }

        context.addClass(tiCostRemovalYes);
        alignComplementCards(context);

    } else {
        context.removeClass(tiCostRemovalYes);
        context.removeClass(tiCostRemovalAdd);
        context.removeClass(tiCostTrimmingStr);
    }
}

function alignComplementCards(context) {

    var headerLineHeight = parseInt(complementCardHeader.css('line-height')),
        headerRows = [],
        listHeights = [];

    context.find(complemHeadStr).removeClass('complem__head-1 complem__head-2 complem__head-3');
    context.find(complementCardList).css('height', 'auto');

    complementCardHeader.each(function (index, value) {
        $clamp(value, {clamp: 3});
    });

    if (window.innerWidth > 767) {
        context.find(complemStr).each(function () {
            var headerHeight = parseInt($(this).find(complemHeadStr).css('height'));
            headerRows.push(headerHeight / headerLineHeight);

            var listHeight = parseInt($(this).find(complementCardList).css('height'));
            listHeights.push(listHeight);
        });

        var headerMaxRows = Math.max.apply(null, headerRows);
        context.find(complemHeadStr).addClass('complem__head-' + headerMaxRows);


        var listMaxHeight = Math.max.apply(null, listHeights);
        context.find(complementCardList).css('height', listMaxHeight);
    }
}

$(window).on('resize', _.debounce(function () {
    $('.ti__cost_removal-threshold').each(function () {
        if ($(this).css('display') === 'block') {
            var context = $(this).closest(costRemovalStr);
            alignComplementCards(context)
        }
    })
}, 200));


