<template>
    <buttonQuestion
        ref="buttonQuestion"
        v-model="selectedPackageName"
        :answers="servicePackageAnswers"
        :groupName="groupName"
        buttonTypeString="servicePackageRadio"
        :buttonTypeObject="servicePackageRadio"
        :validationRules="validationRules"
        :isRequired="isRequired" />
</template>

<script>
import buttonQuestion from '@/digital-components/button-question/button-question.vue';
import { processIfStatements } from '@/helpers/cms-content-helper';
import damageLocationsSelected from '@/constants/damage-locations-selected';
import servicePackageRadio from '@/layouts/service-packages/service-package-question/service-package-radio/service-package-radio.vue';
import partTypeStrings from '@/constants/part-type-strings';
import { useMainStore } from '@/store';
import allGlassPartsAndItemsHavePrices from '@/layouts/service-packages/service-package-helper/service-package-helper';
import { getPriceOfLineItem } from '@/helpers/price-calculator';
import { getHighestFullySatisfiedTier } from '@/helpers/service-package-helper.js';

const glassLocations = damageLocationsSelected;

const packageNames = {
    TIER_ONE: 'TierOne',
    TIER_TWO: 'TierTwo',
    TIER_THREE: 'TierThree'
};

const store = useMainStore();

export default {
    name: 'service-package-question',
    components: {
        buttonQuestion
    },
    props: {
        cmsWidgetName: String,
        groupName: String,
        validationRules: String,
        isRequired: Boolean,
        availableLineItems: {
            type: Array,
            default: () => []
        }
    },
    emits: ['vapsItemsSelected'],
    data() {
        return {
            servicePackageRadio,
            selectedPackageName: ''
        };
    },
    computed: {
        nullSafeAvailableLineItems() {
            if (this.availableLineItems?.lineItems) {
                return this.availableLineItems.lineItems;
            }

            return this.availableLineItems ?? [];
        },
        servicePackageAnswers() {
            if (!this.cmsWidgetName) return [];
            const cmsAnswersContent = [];
            if (this.shouldDisplayTierTwoPackage) {
                cmsAnswersContent.push({
                    Name: 'TierTwo',
                    cmsWidgetName: 'StandardServicePackage'
                });
            }
            cmsAnswersContent.push({
                Name: 'TierThree',
                cmsWidgetName: 'PremiumServicePackage'
            });
            cmsAnswersContent.push({
                Name: 'TierOne',
                cmsWidgetName: 'EconomyServicePackage'
            });
            // if cms content has not yet loaded, skip
            if (!this.getCmsContent(cmsAnswersContent[0].cmsWidgetName, 'HeaderText')
                || this.getCmsContent(cmsAnswersContent[0].cmsWidgetName, 'HeaderText') === '') {
                return {};
            }
            const modifiedAnswers = cmsAnswersContent.map((answer) => ({
                value: answer.Name,
                buttonLabel: this.getHeaderTextFromCms(answer.cmsWidgetName),
                buttonLabelSubCopy: this.getSubheaderTextFromCms(answer.cmsWidgetName),
                buttonBodyCopy: this.getBodyTextFromCms(answer.cmsWidgetName),
                buttonAuxiliaryCopy: this.getPackagePriceString(answer.Name),
                buttonFooterCopy: this.getFooterTextFromCms(answer.cmsWidgetName)
            }
            ));
            return modifiedAnswers;
        },
        isRecalibrationOnOrder() {
            return this.lineItemsContainsPartType(partTypeStrings.RECALIBRATION);
        },
        frontWipersApplicableForTierTwo() {
            const frontWipersAreAvailable = this.lineItemsContainsPartType(partTypeStrings.FRONT_WIPER);
            const glassToReplaceContainsWindshield = this.glassToReplaceContainsGlassLocation(glassLocations.WINDSHIELD);

            if (frontWipersAreAvailable && (useMainStore().order.damage.isRepair || glassToReplaceContainsWindshield)) {
                return true;
            }

            return false;
        },
        rearWiperApplicableForTierTwo() {
            const rearWiperIsAvailable = this.lineItemsContainsPartType(partTypeStrings.REAR_WIPER);
            return (
                this.glassToReplaceContainsGlassLocation(glassLocations.REAR)
                    && rearWiperIsAvailable
            );
        },
        frontWipersApplicableForTierThree() {
            const frontWipersAreAvailable = this.lineItemsContainsPartType(partTypeStrings.FRONT_WIPER);
            return frontWipersAreAvailable;
        },
        rearWiperApplicableForTierThree() {
            const rearWiperIsAvailable = this.lineItemsContainsPartType(partTypeStrings.REAR_WIPER);
            const frontWipersAreAvailable = this.lineItemsContainsPartType(partTypeStrings.FRONT_WIPER);
            return (
                rearWiperIsAvailable
                    && (this.glassToReplaceContainsGlassLocation(glassLocations.REAR)
                        || !frontWipersAreAvailable)
            );
        },
        rainDefenseApplicableForTierThree() {
            if (
                this.rearWiperApplicableForTierTwo
                    && !this.frontWipersApplicableForTierTwo
                    && this.frontWipersApplicableForTierThree
            ) {
                return false;
            }
            return true;
        },
        shouldDisplayTierTwoPackage() {
            return this.frontWipersApplicableForTierTwo || this.rearWiperApplicableForTierTwo;
        }
    },
    watch: {
        availableLineItems() {
            this.selectDefaultPackage();
        },
        selectedPackageName(newValue) {
            const VapsProductsInSelectedPackage = this.getVapsLineItemsForSelectedPackage(newValue);
            this.$emit('vapsItemsSelected', VapsProductsInSelectedPackage);
        }
    },
    methods: {
        processIfStatements,
        getHeaderTextFromCms(cmsWidgetName) {
            return this.getCmsContent(cmsWidgetName, 'HeaderText');
        },
        getSubheaderTextFromCms(cmsWidgetName) {
            return this.getCmsContent(cmsWidgetName, 'SubheaderText');
        },
        getBodyTextFromCms(cmsWidgetName) {
            const bodyText = this.getCmsContent(cmsWidgetName, 'BodyText');
            return this.processIfStatements(bodyText, 'custom', this.getCustomValueFromString);
        },
        getFooterTextFromCms(cmsWidgetName) {
            const footerText = this.getCmsContent(cmsWidgetName, 'FooterText');
            return this.processIfStatements(footerText, 'custom', this.getCustomValueFromString);
        },
        getPackagePriceString(packageName) {
            const formattedPriceFloat = parseFloat(this.getPackagePrice(packageName)).toFixed(2);
            return `+$${formattedPriceFloat}*`;
        },
        getPackagePrice(packageName) {
            let priceFloat = 0;
            if (packageName === packageNames.TIER_TWO) {
                priceFloat += this.getTierTwoPackageVapsPrice();
            } else if (packageName === packageNames.TIER_THREE) {
                priceFloat += this.getTierThreePackageVapsPrice();
            }
            return priceFloat;
        },
        getTierTwoPackageVapsPrice() {
            let vapsPrice = 0;
            const priceFrontWipers = this.frontWipersApplicableForTierTwo;
            const priceRearWipers = this.rearWiperApplicableForTierTwo;
            this.nullSafeAvailableLineItems.forEach((item) => {
                if (
                    (priceFrontWipers
                            && item.partType.toUpperCase() === partTypeStrings.FRONT_WIPER)
                        || (priceRearWipers && item.partType.toUpperCase() === partTypeStrings.REAR_WIPER)
                ) {
                    vapsPrice += getPriceOfLineItem(item);
                }
            });
            return vapsPrice;
        },
        getTierThreePackageVapsPrice() {
            let vapsPrice = 0;
            const priceFrontWipers = this.frontWipersApplicableForTierThree;
            const priceRearWipers = this.rearWiperApplicableForTierThree;
            const priceRainDefense = this.rainDefenseApplicableForTierThree;
            this.nullSafeAvailableLineItems.forEach((item) => {
                if (
                    (priceFrontWipers
                            && item.partType.toUpperCase() === partTypeStrings.FRONT_WIPER)
                        || (priceRearWipers
                            && item.partType.toUpperCase() === partTypeStrings.REAR_WIPER)
                        || (priceRainDefense
                            && item.partType.toUpperCase() === partTypeStrings.RAIN_DEFENSE)
                ) {
                    vapsPrice += getPriceOfLineItem(item);
                }
            });
            return vapsPrice;
        },
        selectDefaultPackage() {
            const { glassToReplace, isRepair } = store.order.damage;
            const { vaps } = store.order.lineItems;
            const defaultTier = getHighestFullySatisfiedTier(
                glassToReplace ?? [],
                this.availableLineItems,
                isRepair,
                vaps ?? []
            );
            this.selectedPackageName = defaultTier;
        },
        getVapsLineItemsForSelectedPackage(packageName) {
            const vapsLineItemsForSelectedPackage = [];
            if (packageName === packageNames.TIER_TWO) {
                if (this.frontWipersApplicableForTierTwo) {
                    vapsLineItemsForSelectedPackage.push(...this.getLineItemsContainingPartType(partTypeStrings.FRONT_WIPER));
                }
                if (this.rearWiperApplicableForTierTwo) {
                    vapsLineItemsForSelectedPackage.push(...this.getLineItemsContainingPartType(partTypeStrings.REAR_WIPER));
                }
            } else if (packageName === packageNames.TIER_THREE) {
                if (this.frontWipersApplicableForTierThree) {
                    vapsLineItemsForSelectedPackage.push(...this.getLineItemsContainingPartType(partTypeStrings.FRONT_WIPER));
                }
                if (this.rearWiperApplicableForTierThree) {
                    vapsLineItemsForSelectedPackage.push(...this.getLineItemsContainingPartType(partTypeStrings.REAR_WIPER));
                }
                if (this.rainDefenseApplicableForTierThree) {
                    vapsLineItemsForSelectedPackage.push(...this.getLineItemsContainingPartType(partTypeStrings.RAIN_DEFENSE));
                }
            }
            return vapsLineItemsForSelectedPackage;
        },
        getCustomValueFromString(str) {
            switch (str) {
                case 'isRecalibrationOnOrder':
                    return this.isRecalibrationOnOrder;
                case 'frontWipersApplicableForTierTwo':
                    return this.frontWipersApplicableForTierTwo;
                case 'rearWiperApplicableForTierTwo':
                    return this.rearWiperApplicableForTierTwo;
                case 'frontWipersApplicableForTierThree':
                    return this.frontWipersApplicableForTierThree;
                case 'rearWiperApplicableForTierThree':
                    return this.rearWiperApplicableForTierThree;
                case 'rainDefenseApplicableForTierThree':
                    return this.rainDefenseApplicableForTierThree;
                default:
                    return null;
            }
        },
        getLineItemsContainingPartType(partType) {
            const partTypeMatches = this.nullSafeAvailableLineItems.filter((lineItem) => lineItem.partType.toUpperCase() === partType);
            return partTypeMatches;
        },
        lineItemsContainsPartType(partType) {
            const partTypeMatches = this.getLineItemsContainingPartType(partType);
            return !!partTypeMatches.length;
        },
        glassToReplaceContainsGlassLocation(glassLocation) {
            const glassLocationMatches =
                store.order.damage.glassToReplace?.filter((glassToReplace) => glassToReplace.glassLocation === glassLocation) ?? [];
            return !!glassLocationMatches.length;
        }
    }
};
</script>
