<template>
    <Form @submit="onSubmit" @invalid-submit="onInvalidSubmit" ref="theForm">
        <div class="page-container-grouped-styles">
            <div class="fade-on-route-transition position-relative">
                <siteHeader cmsWidgetName="SiteHeaderWidget" />
                <siteSubHeader cmsWidgetName="SiteSubHeader" id="sub-header" class="mb-5 mt-4" />

                <buttonQuestion ref="buttonQuestion"
                    questionText="Select an option:"
                    :answers="prefAnswers"
                    groupName="prefQuestions"
                    buttonTypeString="providerPrefRadio"
                    v-model="selectedProvider"
                    validationRules="option-required"
                    isRequired
                    class="mx-5" />
                <div class="px-5">
                    <siteFooter
                        cmsWidgetName="SiteFooterWidget"
                        :isForwardActionDisabled="isForwardActionDisabled"
                        @backClicked="backButtonAction"
                        @forwardClicked="forwardButtonAction"
                        ref="siteFooter" />
                </div>
            </div>
        </div>
        <recalModal ref="recalModal" cmsWidgetName="RecalModal" />
        <steeringModal cmsWidgetName="StateSteeringModal" ref="StateSteeringModal" />
        <shopPreferenceModal 
            cmsWidgetName="ShopPreferenceDrawer" 
            ref="ShopPreferenceDrawer" 
            @openSteering="openStateSteeringModal"
            :showSteeringLink="showSteeringLink"/>
        <tpaRecalModal cmsWidgetName="TPARecalModal" 
            ref="TPARecalModal"
            :ackError="ackError" 
            @buttonClick="navigateWithTPAAck"
            /> 
    </Form>

</template>
<script>
// Import Supporting Files
import { fetchCmsContentForPage, setupModalLinks, processIfStatements } from '@/helpers/cms-content-helper';
import { settleAllPromises } from "@/helpers/layout-helper";
import { required } from "@/helpers/validation-rules";
import { errorMessages } from "@/constants/error-messages";
import buttonQuestion from "@/digital-components/button-question/button-question";
import contentGroupModal from "@/iss-components/content-group-modal/content-group-modal";
import { issPageValues } from "@/router/router-constants/issPage-values";

// Import Component
import baseFormMixin from "@/mixins/base-form-mixin";
import { Form, defineRule } from "vee-validate";
import siteFooter from "@/iss-components/site-footer/site-footer";
import siteHeader from "@/iss-components/site-header/site-header";
import siteSubHeader from "@/iss-components/site-sub-header/site-sub-header";
import providerPrefRadio from "./provider-pref-radio/provider-pref-radio";
import recalModal from "@/layouts/coverage-statement/recal-modal/recal-modal";
import steeringModal from "@/layouts/provider-preference/steering-modal/steering-modal";
import shopPreferenceModal from "@/layouts/provider-preference/shop-preference-modal/shop-preference-modal";
import tpaRecalModal from "@/layouts/provider-preference/tpa-recal-modal/tpa-recal-modal.vue"

// DEFINE VALIDATION RULES
defineRule('option-required', required(errorMessages.OPTION_REQUIRED));
const options = { SAFELITE: 'SafeliteOption', TPA: 'TPAOption' };

export default {
    name: "provider-preference",
    mixins: [baseFormMixin],

    components: {
        siteFooter,
        siteHeader,
        siteSubHeader,
        Form,
        buttonQuestion,
        contentGroupModal,
        providerPrefRadio,
        recalModal,
        steeringModal,
        shopPreferenceModal,
        tpaRecalModal
    },
    data() {
        return {
            selectedProvider : null,
            showSteeringLink: false,
            tpaAcknowledgement: false,
        };
    },
    async beforeRouteEnter(to, from, next) {
        const cmsContentPromise = fetchCmsContentForPage(to.query.issPage);
        // Settle promises and get results
        const promiseResultMap = [
            {
                resultKey: "cmsContent",
                promise: cmsContentPromise,
            },
        ];
        const resultMap = await settleAllPromises(promiseResultMap);
        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);
        });
    },
    computed: {
        isForwardActionDisabled() {
            return this.selectedProvider === null;
        },
        prefAnswers() {
            const cmsAnswersContent = [
                {
                    cmsWidgetName: options.SAFELITE
                },
                {
                    cmsWidgetName: options.TPA
                }
            ];
            //if cms content has not yet loaded, skip
            if (this.getCmsContent(cmsAnswersContent[0].cmsWidgetName, 'HeaderText') == '') {
                return {};
            }
            const modifiedAnswers = cmsAnswersContent.map((answer) => ({
                    value: answer.cmsWidgetName,
                    buttonLabel: this.getHeaderTextFromCms(answer.cmsWidgetName),
                    buttonLabelSubCopy: this.getSubheaderTextFromCms(answer.cmsWidgetName),
                    buttonBodyCopy: this.getBodyTextFromCms(answer.cmsWidgetName),
                }
            ));
            return modifiedAnswers;
        },
        ackError() {
            return errorMessages.ACKNOWLEDGEMENT_REQUIRED;
        }
    },
    methods: {
        getHeaderTextFromCms(cmsWidgetName) {
            const headerText = this.getCmsContent(cmsWidgetName, 'HeaderText');
            return headerText?.replace("{custom:SafeliteLogo}", "<span class='safeliteLogo'></span>");
        },
        getSubheaderTextFromCms(cmsWidgetName) {
            return this.getCmsContent(cmsWidgetName, 'SubheaderText');
        },
        getBodyTextFromCms(cmsWidgetName) {
            return this.getCmsContent(cmsWidgetName, "BodyText");
        },
        arePagePrerequisiteValid() {
            return true;
        },
        backButtonAction() {
            this.$router.navigate(this.navigationScenarios.CLICKED_BACK, this.$route);
        },
        navigateForward(scenario){
            this.$router.navigate(scenario, this.$route);
        },
        navigateWithTPAAck() {
            this.mainStore.saveProviderPreferenceData({selectedProvider: this.selectedProvider, tpaAcknowledgement: this.tpaAcknowledgement}); 
            this.navigateForward(this.navigationScenarios.CLICKED_FORWARD_WITH_TPA_ENABLED);
        },
        forwardButtonAction() {
            if(this.selectedProvider) {
                let scenario = null; 
                switch (this.selectedProvider) {
                    case options.SAFELITE:
                        scenario = this.navigationScenarios.CLICKED_FORWARD_WITH_SAFELITE;
                        break;
                    case options.TPA:
                        if(this.mainStore.issConfig.enableTPAFlow)
                        {
                            if(this.mainStore.hasRecalibrationPart)
                            {
                                this.$refs["TPARecalModal"].openModal();
                                this.$refs["siteFooter"].removeLoader();
                                return;
                            }
                            scenario = this.navigationScenarios.CLICKED_FORWARD_WITH_TPA_ENABLED;
                        }
                        else{
                            scenario = this.navigationScenarios.CLICKED_FORWARD_WITH_TPA_DISABLED;
                        }
                        break;
                };
                this.navigateForward(scenario);
                this.mainStore.saveProviderPreferenceData({selectedProvider: this.selectedProvider, tpaAcknowledgement: this.tpaAcknowledgement}); 
            }
        },
        openStateSteeringModal() {
            this.$refs["StateSteeringModal"].openModal();
        },
        setShowSteeringLink() {
            const bodyText = this.getSteeringModalBody();
            this.showSteeringLink = !!bodyText; 
        },
        getSteeringModalBody() {
            return this.$refs["StateSteeringModal"]?.ModalBodyText;
        }
    },
    mounted() {
        setupModalLinks(this);
        this.setShowSteeringLink();
        
        const pageData = this.mainStore.pageData(issPageValues.PROVIDER_PREFERENCE);
        this.selectedProvider = pageData?.selectedProvider ? pageData.selectedProvider : null;
        this.tpaAcknowledgement = pageData?.tpaAcknowledgement ? pageData.tpaAcknowledgement : false;

        if(this.showSteeringLink) {
            this.openStateSteeringModal();
        }

    }
};
</script>
<style lang="scss" >
#sub-header span{
    color: $black;
}

.modal-link a{
    color: $blue-700;
    font-size: 14px;
    line-height: 24px;
    font-weight: 500;
}
.question-text {
    margin-top: 0;
    margin-bottom: .5rem;
    & > span {
        text-align: left;
    }
}

.safeliteLogo {
    background-image: url(~@/assets/img/icons/safelite-logo.svg);
    background-repeat: no-repeat;
    background-size: 4.5rem;
    margin: 0 0.25rem 0 0.25rem;
    padding: 0 2.5rem 0 2.5rem;

}

</style>
