<template>
    <Form
        ref="theForm"
        v-slot="{ meta }"
        @submit="onSubmit"
        @invalidSubmit="onInvalidSubmit">
        <div class="fade-on-route-transition service-packages">
            <div class="justify-content-center">
                <siteHeader cmsWidgetName="SiteHeaderWidget" />
            </div>
            <div class="iss-heritage-container-width">
                <div class="service-packages-container iss-heritage-content-container-width">
                    <siteSubHeader
                        class="mt-4"
                        subHeaderClasses="mt-5"
                        justification="left"
                        cmsWidgetName="SiteSubHeaderWidget"
                        issContainingPage="service-packages" />
                    <servicePackageQuestion
                        ref="servicePackage"
                        cmsWidgetName="ServicePackage"
                        groupName="ServicePackageQuestion"
                        :availableLineItems="availableLineItems"
                        :validationRules="rules.optionRequired"
                        isRequired
                        @vapsItemsSelected="vapsItemsSelectedAction"
                        @link-event="openModalAction" />
                    <p
                        class="caption disclaimer"
                        v-html="PriceDisclaimerText"></p>
                    <siteFooter
                        cmsWidgetName="SiteFooterWidget"
                        :isForwardActionDisabled="!meta.valid"
                        @backClicked="navigateBack"
                        @ForwardClicked="forwardButtonAction" />
                </div>
            </div>
            <loadingModal
                ref="loadingModal"
                :textSlides="loadingText" />
            <contentGroupModal
                ref="RainDefenseModal"
                cmsWidgetName="RainDefenseModal" />
            <contentGroupModal
                ref="FrontWiperModal"
                cmsWidgetName="FrontWiperModal" />
            <contentGroupModal
                ref="RearWiperModal"
                cmsWidgetName="RearWiperModal" />
            <contentGroupModal
                ref="RecalModal"
                cssModalHeadlineClass="text-center"
                cmsWidgetName="RecalModal" />
        </div>
    </Form>
</template>

<script>
// Components
import baseFormMixin from '@/mixins/base-form-mixin';
import siteHeader from '@/iss-components/site-header/site-header.vue';
import siteFooter from '@/iss-components/site-footer/site-footer.vue';
import siteSubHeader from '@/iss-components/site-sub-header/site-sub-header.vue';
import contentGroupModal from '@/iss-components/content-group-modal/content-group-modal.vue';
import loadingModal from '@/iss-components/loading-modal/loading-modal.vue';
import settleAllPromises from '@/helpers/layout-helper';
import { useMainStore } from '@/store';
import { fetchCmsContentForPage } from '@/helpers/cms-content-helper';
import { Form } from 'vee-validate';
import allGlassPartsAndItemsHavePrices from '@/layouts/service-packages/service-package-helper/service-package-helper';
import globalRules from '@/constants/global-rules';
import servicePackageQuestion from '@/layouts/service-packages/service-package-question/service-package-question.vue';
import issPageValues from '@/router/router-constants/issPage-values';
import bailoutMessage from '@/constants/bailoutMessage';

const store = useMainStore();

export default {
    name: 'service-packages',
    components: {
        siteHeader,
        siteFooter,
        siteSubHeader,
        // eslint-disable-next-line vue/no-reserved-component-names
        Form,
        servicePackageQuestion,
        loadingModal,
        contentGroupModal
    },
    mixins: [baseFormMixin],
    async beforeRouteEnter(to, from, next) {
        // Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to.query.issPage);

        const wipersPromise = await store.getWipers();
        const rainDefensePromise = await store.getRainDefense();
        const promiseResultMap = [
            {
                resultKey: 'cmsContent',
                promise: cmsContentPromise
            },
            {
                resultKey: 'wipers',
                promise: wipersPromise
            },
            {
                resultKey: 'rainDefense',
                promise: rainDefensePromise
            }
        ];
        const resultMap = await settleAllPromises(promiseResultMap);

        const { feeItems } = store.order.lineItems;

        const availableLineItems = [];

        if (resultMap?.rainDefense) {
            availableLineItems.push(resultMap.rainDefense);
        }

        if (resultMap?.wipers?.length > 0) {
            availableLineItems.push(...resultMap.wipers);
        }

        if (feeItems?.length > 0) {
            availableLineItems.push(...feeItems);
        }

        let hasBailedOut = false;
        const pricedItems = await store.getCombinedQuote(availableLineItems)
            .catch((err) => {
                useMainStore().setBailout(bailoutMessage.pricingResponseError(
                    availableLineItems.map((li) => li.partNumber),
                    { code: err.code, message: err.message, data: err.data }
                ));
                hasBailedOut = true;
                next(`/?issPage=${issPageValues.BAILOUT_PAGE}`);
            });

        // Call the "next" function to complete the transition to this page.
        if (!hasBailedOut) {
            next((vm) => {
                vm.setCmsContent(resultMap.cmsContent);
                vm.setData(pricedItems);
            });
        }
    },
    data() {
        return {
            selectedVaps: [],
            availableLineItems: [],
            loadingText: [
                'Finding shops near you',
                'Looking for dates',
                'Searching for times',
                'Nearly there',
                'Finishing up'
            ],
            rules: {
                optionRequired: globalRules.OPTION_REQUIRED
            }
        };
    },
    computed: {
        PriceDisclaimerText() {
            return this.getCmsContent('PriceDisclaimerWidget', 'Text');
        }
    },
    methods: {
        openModalAction(modalName) {
            this.$refs[modalName.args].openModal();
        },
        arePagePrerequisitesValid() {
            return (
                store.order.serviceLocation.zipCode
                && store.order.serviceLocation.zipCodeCtu
                && (store.order.damage.isRepair
                    || (store.order.lineItems?.glassParts != null
                        && store.order.lineItems.glassParts.length > 0))
            );
        },
        setData(pricedVaps) {
            this.availableLineItems = pricedVaps;
            useMainStore().order.availableVaps = pricedVaps;
        },
        vapsItemsSelectedAction(vapsItemsSelected) {
            this.selectedVaps = vapsItemsSelected;
        },
        forwardButtonAction() {
            const parts = {
                vaps: this.selectedVaps
            };
            if (!allGlassPartsAndItemsHavePrices(parts)) {
                window.console.error('One or more items have no price assigned!');
            }
            store.updateVaps(this.selectedVaps);

            this.$router.navigate(
                this.navigationScenarios.CLICKED_FORWARD,
                this.$route
            );
        }
    }
};
</script>
<style lang="scss" scoped>
.iss-heritage-container-width {
    .service-packages-container {
        position: relative;
        min-height: 1px;
        padding-left: .9375rem;
        padding-right: .9375rem;
    }
}

.subheader-secondary {
    margin-top: 0.5rem;
    padding: 0px;
}

.disclaimer {
    margin: 0.5rem 0 1.5rem 0;

    a {
        color: #4d5151;
        font-weight: 400;
    }
}
.service-packages {
    :deep(strong) {
        font-weight: $font-weight-bold;
    }
}

</style>
