<template>
    <Form @submit="onSubmit" 
          @invalid-submit="onInvalidSubmit" 
          ref="theForm"  
          v-slot="{ meta }" >
        <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" />
                <buttonQuestion ref="buttonQuestion"
                    :answers="prefAnswers"
                    :groupName="prefQuestions"
                    buttonTypeString="providerPrefRadio"
                    :buttonTypeObject="providerPrefRadio"
                    v-model="selectedProvider"
                    :validationRules="option-required"
                    :isRequired="isRequired"
                    class="mx-4" />
                
                <siteFooter
                    cmsWidgetName="SiteFooterWidget"
                    :isForwardActionDisabled="isForwardActionDisabled"
                    @backClicked="backButtonAction"
                    @forwardClicked="forwardButtonAction"
                    ref="siteFooter" />
            </div>

        </div>
        <contentGroupModal cmsWidgetName="ShopPreferenceDrawer"
                        ref="ShopPreferenceDrawer"
                    />
        <modal
            ref="SteeringModal"
            modalId="SteeringModal"
            @footer-button-event="closeSteeringModal"
            :footerButtonText="steeringModalFooter">
            <h5 class="text-center">{{steeringModalHeader}}</h5>
            <div class="steeringModalBody">
                <div class="mb-4" >{{steeringModalBody}}</div>
                <div v-if="steeringModalBody2">{{steeringModalBody2}}</div>
            </div>
        </modal>
    </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 modal from "@/digital-components/modal/modal" 
import { states } from "@/constants/states"

// 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.vue"

// DEFINE VALIDATION RULES
defineRule('option-required', required(errorMessages.OPTION_REQUIRED));

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

    components: {
        siteFooter,
        siteHeader,
        siteSubHeader,
        Form,
        buttonQuestion,
        contentGroupModal,
        modal,
        providerPrefRadio
    },
    data() {
        return {
            selectedProvider : null,
        };
    },
    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;
        },

        ProviderPreferenceHeaderText(){
            return this.getCmsContent("ProviderPreference", "HeaderText");
        },
        questionText() {
            return this.getCmsContent("ProviderPreference", "SubHeaderText");
        },
        
        prefAnswers() {
            const cmsAnswersContent = [
                {
                    cmsWidgetName: 'SafeliteOption'
                },
                {
                    cmsWidgetName: 'TPAOption'
                }
            ];
            //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),
                    buttonFooterCopy: this.getFooterTextFromCms(answer.cmsWidgetName)
                }
            ));
            return modifiedAnswers;
        },

        steeringModalHeader() {
            let header = this.getCmsContent("StateSteeringModal", "HeaderText");
            return header.replace("{custom:state}", states[this.mainStore.order.customer.address.state])
        },
        steeringModalBody() {
            const bodyText = this.getCmsContent("StateSteeringModal", "BodyText");
            return processIfStatements(bodyText, "custom", this.getStateSpecificText); 
        },
        steeringModalBody2() {
            const bodyText = this.getCmsContent("StateSteeringModal", "BodyText2");
            return processIfStatements(bodyText, "custom", this.getStateSpecificText); 
        },
        steeringModalFooter() {
            return this.getCmsContent("StateSteeringModal", "FooterText");
        }
    },
    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) {
            const bodyText = this.getCmsContent(cmsWidgetName, "BodyText");
            return processIfStatements(bodyText, "custom", this.getCustomValueFromString);
        },
        getFooterTextFromCms(cmsWidgetName) {
            const footerText = this.getCmsContent(cmsWidgetName, "FooterText");
            return processIfStatements(footerText, "custom", this.getCustomValueFromString);
        },
        getStateSpecificText(value) {
            return this.mainStore.order.customer.address.state?.toLowerCase() == value?.toLowerCase();
        },
        arePagePrerequisiteValid() {
            return true;
        },
        backButtonAction() {
            /**
            * this.navigationScenarios comes from base-mixin
            */
            this.$router.navigate(this.navigationScenarios.CLICKED_BACK, this.$route);
        },
        forwardButtonAction() {
            //todo
            this.$router.navigate(this.navigationScenarios.CLICKED_FORWARD_WITH_SAFELITE, this.$route);
            //if(this.selectedProvider == "Schedule with Safelite")
            //{
            //    this.$router.navigate(this.navigationScenarios.CLICKED_FORWARD_WITH_SAFELITE, this.$route);
            //}
        },
        closeSteeringModal() {
            this.$refs["SteeringModal"].closeModal();
        }
    },
    mounted() {
        setupModalLinks(this);
        if(this.steeringModalBody) {
            this.$refs["SteeringModal"].openModal();
        }
    }
};
</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;
    & > 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>
