<template>
    <Form
        ref="theForm"
        @submit="onSubmit"
        @invalidSubmit="onInvalidSubmit">
        <div class="page-container-grouped-styles">
            <div class="fade-on-route-transition position-relative">
                <siteHeader cmsWidgetName="SiteHeaderWidget" />
                <siteSubHeader
                    id="sub-header"
                    cmsWidgetName="SiteSubHeader"
                    class="mb-5 mt-4" />
                <buttonQuestion
                    ref="buttonQuestion"
                    v-model="selectedProvider"
                    questionText="Select an option:"
                    :answers="prefAnswers"
                    groupName="prefQuestions"
                    buttonTypeString="providerPrefRadio"
                    :validationRules="rules.optionRequired"
                    isRequired
                    class="mx-5" />
                <div class="px-5">
                    <siteFooter
                        ref="siteFooter"
                        class="mt-5"
                        cmsWidgetName="SiteFooterWidget"
                        :isForwardActionDisabled="isForwardActionDisabled"
                        @backClicked="navigateBack"
                        @forwardClicked="forwardButtonAction" />
                </div>
            </div>
        </div>
        <recalModal
            ref="recalModal"
            cmsWidgetName="RecalModal" />
        <steeringModal
            ref="StateSteeringModal"
            cmsWidgetName="StateSteeringModal" />
        <shopPreferenceModal
            ref="ShopPreferenceDrawer"
            cmsWidgetName="ShopPreferenceDrawer"
            :showSteeringLink="showSteeringLink"
            @openSteering="openStateSteeringModal" />
        <tpaRecalModal
            ref="TPARecalModal"
            cmsWidgetName="TPARecalModal"
            :ackError="ackError"
            @buttonClick="navigateWithTPAAck" />
    </Form>
</template>
<script>
// Import Supporting Files
import { fetchCmsContentForPage, setupModalLinks } from '@/helpers/cms-content-helper';
import settleAllPromises from '@/helpers/layout-helper';
import errorMessages from '@/constants/error-messages';
import buttonQuestion from '@/digital-components/button-question/button-question.vue';
import issPageValues from '@/router/router-constants/issPage-values';

// Import Component
import baseFormMixin from '@/mixins/base-form-mixin';
import { Form } from 'vee-validate';
import siteFooter from '@/iss-components/site-footer/site-footer.vue';
import siteHeader from '@/iss-components/site-header/site-header.vue';
import siteSubHeader from '@/iss-components/site-sub-header/site-sub-header.vue';
import recalModal from '@/layouts/coverage-statement/recal-modal/recal-modal.vue';
import steeringModal from '@/layouts/provider-preference/steering-modal/steering-modal.vue';
import shopPreferenceModal from '@/layouts/provider-preference/shop-preference-modal/shop-preference-modal.vue';
import tpaRecalModal from '@/layouts/provider-preference/tpa-recal-modal/tpa-recal-modal.vue';
import globalRules from '@/constants/global-rules';
import bailoutCode from '@/constants/bailoutCode';
import bailoutMessage from "@/constants/bailoutMessage";

const options = { SAFELITE: 'SafeliteOption', TPA: 'TPAOption' };

export default {
    name: 'provider-preference',

    components: {
        siteFooter,
        siteHeader,
        siteSubHeader,
        // eslint-disable-next-line vue/no-reserved-component-names
        Form,
        buttonQuestion,
        recalModal,
        steeringModal,
        shopPreferenceModal,
        tpaRecalModal
    },
    mixins: [baseFormMixin],
    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);

            vm.showSteeringLink = !!vm.$refs.StateSteeringModal.ModalBodyText;
            if (vm.showSteeringLink) {
                vm.$refs.StateSteeringModal.openModal();
            }
        });
    },
    data() {
        return {
            selectedProvider: null,
            showSteeringLink: false,
            tpaAcknowledgement: false,
            rules: {
                optionRequired: globalRules.OPTION_REQUIRED
            }
        };
    },
    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')
                || 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;
        }
    },
    mounted() {
        setupModalLinks(this);
        const pageData = this.mainStore.pageData(issPageValues.PROVIDER_PREFERENCE);
        this.selectedProvider = pageData?.selectedProvider ? pageData.selectedProvider : null;
        this.tpaAcknowledgement = pageData?.tpaAcknowledgement ? pageData.tpaAcknowledgement : false;
    },
    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;
        },
        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:
                        this.mainStore.updateIsSafeliteProvider(true);
                        scenario = this.navigationScenarios.CLICKED_FORWARD_WITH_SAFELITE;
                        break;
                    case options.TPA:
                        this.mainStore.updateIsSafeliteProvider(false);
                        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 {
                            this.mainStore.setBailout(bailoutMessage.TPANotEnabled());
                            scenario = this.navigationScenarios.CLICKED_FORWARD_WITH_TPA_DISABLED;
                        }
                        break;
                    default:
                }
                this.navigateForward(scenario);
                this.mainStore.saveProviderPreferenceData({
                    selectedProvider: this.selectedProvider,
                    tpaAcknowledgement: this.tpaAcknowledgement
                });
            }
        },
        openStateSteeringModal() {
            this.$refs.StateSteeringModal.openModal();
        }
    }
};
</script>
<style lang="scss" scoped>
#sub-header span {
    color: $black;
}

.question-text {
    margin-top: 0;
    margin-bottom: 0.5rem;
    & > span {
        text-align: left;
    }
}

:deep(.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>
