<template>
    <Form
        ref="theForm"
        @submit="onSubmit"
        @invalidSubmit="onInvalidSubmit">
        <div class="fade-on-route-transition provider-preference">
            <div class="justify-content-center">
                <siteHeader
                    class="mt-4 header"
                    cmsWidgetName="SiteHeaderWidget" />
            </div>
            <div class="iss-heritage-container-width">
                <div class="provider-preference-container iss-heritage-content-container-width">
                    <siteSubHeader
                        id="sub-header"
                        cmsWidgetName="SiteSubHeader"
                        class="mb-0 mt-4 text-center" />
                    <div
                        v-html="scheduleWithSafeliteText"></div>
                    <buttonMain
                        ref="buttonMain"
                        variant="navigation"
                        buttonText="Schedule now"
                        @clickEvent="forwardButtonAction(options.SAFELITE)" />
                    <div
                        v-html="scheduleWithOtherText"></div>
                    <textLink
                        linkType="navigation"
                        text="Find another shop"    
                        href="#"
                        @clickEvent="forwardButtonAction(options.TPA)" />
                    <siteFooter
                        :ref="SITE_FOOTER_REF_NAME"
                        class="mt-5"
                        cmsWidgetName="SiteFooterWidget"
                        :isForwardButtonHidden="true"
                        @backClicked="navigateBack" />
                </div>
            </div>
        </div>
        <steeringModal
            :ref="STEERING_MODAL_REF_NAME"
            cmsWidgetName="StateSteeringModal" />
        <tpaRecalModal
            :ref="TPA_RECAL_MODAL_REF_NAME"
            cmsWidgetName="TPARecalModal"
            :ackError="ackError"
            @buttonClick="navigateWithTPAAck" />
    </Form>
</template>
<script>
// Import Supporting Files
import {
    fetchCmsContentForPage,
    setupModalLink,
    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 showIssLoadingModal from '@/helpers/loading-modal-helper';

// 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 steeringModal from '@/layouts/provider-preference/steering-modal/steering-modal.vue';
import tpaRecalModal from '@/layouts/provider-preference/tpa-recal-modal/tpa-recal-modal.vue';
import globalRules from '@/constants/global-rules';
import bailoutMessage from '@/constants/bailoutMessage';
import contentGroupModal from '@/iss-components/content-group-modal/content-group-modal.vue';
import textLink from '@/ux-components/text-link/text-link.vue';
import buttonMain from '@/ux-components/button-main/button-main.vue';

const options = { SAFELITE: 'SafeliteOption', TPA: 'TPAOption' };
const STEERING_MODAL_REF_NAME = 'StateSteeringModal';
const TPA_RECAL_MODAL_REF_NAME = 'TPARecalModal';
const SITE_FOOTER_REF_NAME = 'siteFooter';

export default {
    name: 'provider-preference',
    components: {
        siteFooter,
        siteHeader,
        siteSubHeader,
        // eslint-disable-next-line vue/no-reserved-component-names
        Form,
        buttonQuestion,
        buttonMain,
        steeringModal,
        tpaRecalModal,
        contentGroupModal,
        textLink
    },
    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);
            if (!!vm.$refs[STEERING_MODAL_REF_NAME].ModalBodyText) {
                vm.openStateSteeringModal();
            }
        });
    },
    data() {
        return {
            selectedProvider: null,
            tpaAcknowledgement: false,
            rules: {
                optionRequired: globalRules.OPTION_REQUIRED
            },
            STEERING_MODAL_REF_NAME,
            TPA_RECAL_MODAL_REF_NAME,
            SITE_FOOTER_REF_NAME
        };
    },
    computed: {
        isForwardActionDisabled() {
            return this.selectedProvider === null;
        },
        isForwardNavigationDisabled() {
            return this.selectedProvider === options.TPA && !this.tpaAcknowledgement;
        },
        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;
        },
        scheduleWithSafeliteText() {
            return this.getCmsContent('ScheduleWithSafeliteText', 'BodyText');
        },
        scheduleWithOtherText() {
            return this.getCmsContent('ScheduleWithOtherText', 'BodyText');
        },
        options() {
            return options;
        }
    },
    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
            });
            showIssLoadingModal(true);
            this.navigateForward(this.navigationScenarios.CLICKED_FORWARD_WITH_TPA_ENABLED);
        },
        forwardButtonAction(selectedProvider) {
            console.log('forwardButtonAction', selectedProvider);
            let scenario = null;
            switch (selectedProvider) {
                case options.SAFELITE:
                    this.mainStore.updateIsSafeliteProvider(true);
                    scenario =
                        this.navigationScenarios
                            .CLICKED_FORWARD_WITH_SAFELITE;
                    break;
                case options.TPA:
                    this.mainStore.updateIsSafeliteProvider(false);
                    console.log('enableTPAFlow', this.mainStore.issConfig.enableTPAFlow);
                    if (this.mainStore.issConfig.enableTPAFlow) {
                        console.log('hasRecalibrationPart', this.mainStore.hasRecalibrationPart);
                        if (this.mainStore.hasRecalibrationPart) {
                            this.$refs[TPA_RECAL_MODAL_REF_NAME].openModal();
                            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);
            showIssLoadingModal(true);
            this.mainStore.saveProviderPreferenceData({
                selectedProvider: selectedProvider,
                tpaAcknowledgement: this.tpaAcknowledgement
            });
        },
        openStateSteeringModal() {
            this.$refs[STEERING_MODAL_REF_NAME].openModal();
        }
    }
};
</script>
<style lang="scss" scoped>
.iss-heritage-container-width {
    .provider-preference-container {
        position: relative;
        min-height: 1px;
        padding-left: .9375rem;
        padding-right: .9375rem;
    }
}

.provider-preference {
    #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/logo.svg);
        background-repeat: no-repeat;
        background-size: 4.5rem;
        margin: 0 0.25rem 0 0.25rem;
        padding: 0 2.5rem 0 2.5rem;
        background-position: center;
    }
}
</style>
