<template>
    <Form
        ref="theForm"
        v-slot="{ meta }"
        @submit="onSubmit"
        @invalidSubmit="onInvalidSubmit">
        <div class="fade-on-route-transition">
            <div class="justify-content-center">
                <siteHeader
                    ref="siteHeader"
                    cmsWidgetName="SiteHeaderWidget" />
            </div>
            <div class="iss-heritage-container-width">
                <div class="bailout-page-container iss-heritage-content-container-width">
                    <siteSubHeader
                        ref="siteSubHeader"
                        :cmsWidgetName="subHeaderCmsWidgetName"
                        :contentProperty="subHeaderContentProperty"
                        :stripRteStyle="stripRteStyle"
                        :subContentProperty="subContentProperty"
                        class="sub-header-content mt-2 mb-5"
                        justification="left" />
                    <textboxQuestion
                        ref="firstName"
                        v-model="bailoutPageModel.firstName"
                        class="mb-3"
                        inputId="firstNameField"
                        cmsWidgetName="FirstNameQuestion"
                        isRequired
                        disableAutoFill
                        :validationRules="rules.firstName" />
                    <textboxQuestion
                        ref="lastName"
                        v-model="bailoutPageModel.lastName"
                        class="mb-3"
                        inputId="lastNameField"
                        cmsWidgetName="LastNameQuestion"
                        isRequired
                        disableAutoFill
                        :validationRules="rules.lastName" />
                    <textboxQuestion
                        ref="phoneNumber"
                        v-model="bailoutPageModel.phoneNumber"
                        class="mb-3"
                        inputId="phoneNumberField"
                        cmsWidgetName="PhoneNumberQuestion"
                        isRequired
                        :mask="phoneMask"
                        disableAutoFill
                        :validationRules="rules.phoneNumber" />
                    <textboxQuestion
                        ref="emailAddress"
                        v-model="bailoutPageModel.email"
                        class="mb-3"
                        inputId="emailAddressField"
                        cmsWidgetName="EmailAddressQuestion"
                        isRequired
                        disableAutoFill
                        :validationRules="rules.email" />
                    <siteFooter
                        ref="siteFooter"
                        class="footer-content-container"
                        cmsWidgetName="SiteFooterWidget"
                        :isForwardActionDisabled="!meta.valid"
                        :isBackButtonHidden="!canNavigateBack"
                        @backClicked="backButtonAction"
                        @ForwardClicked="forwardButtonAction" />
                </div>
            </div>
        </div>
    </Form>
</template>
<script>
// Components
import { Form } from 'vee-validate';
import siteHeader from '@/iss-components/site-header/site-header.vue';
import siteSubHeader from '@/iss-components/site-sub-header/site-sub-header.vue';
import siteFooter from '@/iss-components/site-footer/site-footer.vue';
import textboxQuestion from '@/digital-components/textbox-question/textbox-question.vue';
// Supporting files
import BaseFormMixin from '@/mixins/base-form-mixin.js';
import { fetchCmsContentForPage } from '@/helpers/cms-content-helper';
import globalRules from '@/constants/global-rules';
import settleAllPromises from '@/helpers/layout-helper';
import { useMainStore } from '@/store';
import widgetFields from '@/constants/cms-widget-fields.js';
import routerParams from '@/router/router-constants/router-params';
import canBailoutNavigateBack from '@/helpers/bailout-helper';
import BailoutCode from '@/constants/bailoutCode';
import issPageValues from '@/router/router-constants/issPage-values';
import MaskaFormattedMasks from '@/constants/maska-masks';
import { submitBailout } from '@/helpers/order-helper';

export default {
    name: 'bailout-page',
    components: {
        siteHeader,
        siteSubHeader,
        siteFooter,
        textboxQuestion,
        // eslint-disable-next-line vue/no-reserved-component-names
        Form
    },
    mixins: [BaseFormMixin],
    async beforeRouteEnter(to, from, next) {
        // Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to.query.issPage);
        // Settle promises and get results
        const promiseResultMap = [
            {
                resultKey: 'cmsContent',
                promise: cmsContentPromise
            }
        ];
        // use resultMap to populate layout content.
        const resultMap = await settleAllPromises(promiseResultMap);

        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);
        });
    },
    setup() {
        const mainStore = useMainStore();
        return { mainStore };
    },
    data() {
        return {
            bailoutPageModel: this.getBailoutPageModelFromStore(),
            bailout: this.mainStore.pageData(issPageValues.BAILOUT_PAGE),
            widget: {
                defaultSiteHeader: 'SiteSubHeaderWidget',
                noTpa: 'ContentGroupNoTPAWidget',
                notSeeingPreferredShop: 'ContentGroupNotSeeingPreferredShop'
            },
            rules: {
                firstName: globalRules.FIRST_NAME_REQUIRED,
                lastName: globalRules.LAST_NAME_REQUIRED,
                phoneNumber: `${globalRules.PHONE_NUMBER_REQUIRED}|${globalRules.PHONE_NUMBER_FORMAT}`,
                email: `${globalRules.EMAIL_ADDRESS_REQUIRED}|${globalRules.EMAIL_ADDRESS_FORMAT}`
            }
        };
    },
    computed: {
        subHeaderCmsWidgetName() {
            switch (this.bailout.bailoutCode) {
                case BailoutCode.TPANotEnabled:
                    return this.widget.noTpa;

                case BailoutCode.DoNotSeeMyShop:
                    return this.widget.notSeeingPreferredShop;

                default:
                    return this.widget.defaultSiteHeader;
            }
        },
        subHeaderContentProperty() {
            switch (this.bailout.bailoutCode) {
                case BailoutCode.TPANotEnabled:
                case BailoutCode.DoNotSeeMyShop:
                    return widgetFields.CONTENT_GROUP_WIDGET.HEADER_TEXT;

                default:
                    return widgetFields.SUB_HEADER_WIDGET.SUB_HEADER_TEXT;
            }
        },
        subContentProperty() {
            switch (this.bailout.bailoutCode) {
                case BailoutCode.TPANotEnabled:
                case BailoutCode.DoNotSeeMyShop:
                    return widgetFields.CONTENT_GROUP_WIDGET.BODY_TEXT;

                default:
                    return widgetFields.SUB_HEADER_WIDGET.SECONDARY_TEXT;
            }
        },
        stripRteStyle() {
            switch (this.bailout.bailoutCode) {
                case BailoutCode.TPANotEnabled:
                case BailoutCode.DoNotSeeMyShop:
                    return true;

                default:
                    return false;
            }
        },
        canNavigateBack() {
            return canBailoutNavigateBack();
        },
        phoneMask() {
            return MaskaFormattedMasks.PHONE_NUMBER;
        }
    },
    methods: {
        backButtonAction() {
            // route to move backwards
            this.mainStore.resetBailout();
            this.$router.navigateWithSpinner(
                this.navigationScenarios.CLICKED_BACK_PREVIOUS,
                this.$route
            );
        },
        async forwardButtonAction() {
            this.mainStore.setBailoutContactInfo(this.bailoutPageModel);
            await submitBailout();
            this.$router.navigate(
                this.navigationScenarios.CLICKED_FORWARD,
                this.$route,
                {},
                { [routerParams.SKIP_SAVE_SESSION]: true }
            );
        },
        getBailoutPageModelFromStore() {
            return {
                firstName: useMainStore().order.customer.firstName,
                lastName: useMainStore().order.customer.lastName,
                phoneNumber: useMainStore().order.contactInfo.servicePhone,
                email: useMainStore().order.customer.emailAddress
            };
        }
    }
};
</script>

<style lang="scss">
@import '@/styles/bailout-common.scss';

.iss-heritage-container-width {
    .bailout-page-container {
        position: relative;
        min-height: 1px;
        padding-left: .9375rem;
        padding-right: .9375rem;
    }
}
</style>
