<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" />
                    <div class="row">
                        <div class="col">
                            <textboxQuestion
                                ref="firstName"
                                v-model="bailoutPageModel.firstName"
                                class="input"
                                inputId="firstNameField"
                                cmsWidgetName="FirstNameQuestion"
                                isRequired
                                disableAutoFill
                                :validationRules="rules.firstName" />
                        </div>
                        <div class="col">
                            <textboxQuestion
                                ref="lastName"
                                v-model="bailoutPageModel.lastName"
                                class="input"
                                inputId="lastNameField"
                                cmsWidgetName="LastNameQuestion"
                                isRequired
                                disableAutoFill
                                :validationRules="rules.lastName" />
                        </div>
                    </div>
                    <textboxQuestion
                        ref="phoneNumber"
                        v-model="bailoutPageModel.phoneNumber"
                        class="input"
                        inputId="phoneNumberField"
                        cmsWidgetName="PhoneNumberQuestion"
                        isRequired
                        :mask="phoneMask"
                        disableAutoFill
                        :validationRules="rules.phoneNumber" />
                    <textboxQuestion
                        ref="emailAddress"
                        v-model="bailoutPageModel.email"
                        class="input"
                        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" />
                    <textBlock
                        ref="disclaimerText"
                        cmsWidgetName="DisclaimerWidget" />
                </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';
import textBlock from '@/digital-components/text-block/text-block.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,
        Form,
        textBlock
    },
    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',
                disclaimerText: 'DisclaimerWidget'
            },
            rules: {
                firstName: globalRules.POLICYHOLDER_FIRST_NAME_REQUIRED,
                lastName: globalRules.POLICYHOLDER_LAST_NAME_REQUIRED,
                phoneNumber: `${globalRules.PRIMARY_PHONE_REQUIRED}|${globalRules.PHONE_NUMBER_FORMAT}`,
                email: `${globalRules.BAILOUT_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
            if (this.bailout.bailoutCode !== BailoutCode.HeavyTruckVehicle) {
                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" scoped>
.iss-heritage-container-width {
    .bailout-page-container {
        position: relative;
        min-height: 1px;
        padding-left: .9375rem;
        padding-right: .9375rem;
    }
}

.input {
    margin-bottom: 20px;
}

.footer-content-container {
    margin: 30px 0 30px 0;
}
</style>
