<template>
    <Form @submit="onSubmit" @invalid-submit="onInvalidSubmit" ref="theForm" v-slot="{ meta }">
        <loadingModal ref="loadingModal" />
        <funnelHeader cmsWidgetName="FunnelHeaderWidget" ref="funnelHeader" />
        <div class="container page-container-grouped-styles">
            <div class="row">
                <div class="col-12 col-md-10 col-lg-8 col-xl-7">
                    <funnelSubHeader
                        class="pt-4 pb-2"
                        cmsWidgetName="FunnelSubHeaderWidget"
                        alignLeft />
                    <p class="select-option mb-2" v-html="SelectOptionText"></p>

                    <buttonQuestion
                        cmsWidgetName="VinLookupMethod"
                        :answers="answersFromCms"
                        groupName="vinLookupMethodOption"
                        buttonTypeString="listButton"
                        v-model="selectedVinLookupMethod"
                        isRequired
                        validationRules="option-required"
                        :logDisplayedValuesEvent="true" />
                    <navbar
                        cmsWidgetName="FunnelFooterWidget"
                        ref="navbar"
                        :isForwardActionDisabled="!meta.valid"
                        @back-clicked="backButtonAction"
                        @ForwardClicked="forwardButtonAction" />

                    <div class="text-center mb-5" v-html="this.VinLookupQuestionFooterText2"></div>
                </div>
            </div>
        </div>
    </Form>
</template>

<script>
// Components
import funnelHeader from "@/fmg-components/funnel-header/funnel-header";
import funnelSubHeader from "@/fmg-components/funnel-sub-header/funnel-sub-header";
import navbar from "@/fmg-components/nav-bar/nav-bar";
import buttonQuestion from "@/digital-components/button-question/button-question";
import loadingModal from "@/fmg-components/loading-modal/loading-modal.vue";

//Supporting Files
import { fetchCmsContentForPage } from "@/helpers/cms-content-helper";
import { settleAllPromises } from "@/helpers/layout-helper";
import { required, regex } from "@/helpers/validation-rules";
import { errorMessages } from "@/constants/error-messages";
import { Form, defineRule } from "vee-validate";
import store from "@/store";
import { storeActions } from "@/constants/store-actions";
import { vinLookupMethodSelections } from "@/constants/vin-lookup-method-selections.js";
import {
    skipVinLookup,
    skipVinLookupNotRepair,
} from "@/helpers/heritage-integration/navigation-helper";
import vinPagesMixin from "@/mixins/vin-pages-mixin";
import { navigateToHeritageFunnel } from "@/helpers/heritage-integration/navigation-helper";
import { saveSession } from "@/helpers/heritage-integration/order-helper.js";
import baseMixin from "@/mixins/base-mixin.js";
import { queryStrings } from "@/constants/query-strings";
import { nextTick } from "vue";
import { peekQueryFromStash } from "@/router/methods/helpers/querystring-stash";

// Define Validation Rules
defineRule("zip-required", required(errorMessages.SERVICE_ZIP_REQUIRED));
defineRule("zip-format", regex(/(^\d{5}$)|(^\d{5}-\d{4}$)/, errorMessages.SERVICE_ZIP_FORMAT));
defineRule("email-address-required", required(errorMessages.EMAIL_ADDRESS_REQUIRED));
defineRule(
    "email-address-format",
    regex(
        /^([a-zA-Z0-9_\-.+]+)@([a-zA-Z0-9-]+)\.([a-zA-Z]{2,})$/,
        errorMessages.EMAIL_ADDRESS_FORMAT
    )
);
defineRule("option-required", required(errorMessages.OPTION_REQUIRED));

export default {
    name: "estimate",
    mixins: [vinPagesMixin],
    data() {
        return {
            selectedVinLookupMethod: null,
            skipVin: false,
            skipVinNotRepair: false,
        };
    },

    async beforeRouteEnter(to, from, next) {
        //Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to.name);

        const queryString = window.location.search;
        const urlParams = new URLSearchParams(queryString);
        const lowerCaseParams = new URLSearchParams();
        for (const [name, value] of urlParams) {
            lowerCaseParams.append(name.toLowerCase(), value);
        }

        const zip = store.getters.order.serviceLocation.zipCode;

        var vinByAddressPromise;
        if (zip) {
            vinByAddressPromise = baseMixin.methods.dispatchStoreActionWithLogging(
                storeActions.IS_VIN_BY_ADDRESS_PERMISSIBLE,
                { zip: zip },
                "estimate",
                false
            );
        }

        //Settle promises and get results
        const promiseResultMap = [
            {
                resultKey: "cmsContent",
                promise: cmsContentPromise,
            },
            zip != null &&
                zip != undefined && {
                    resultKey: "vinByAddress",
                    promise: vinByAddressPromise,
                },
        ];

        const resultMap = await settleAllPromises(promiseResultMap);

        next(async (vm) => {
            if (resultMap.cmsContent.FunnelFooterWidget.ForwardButtonText.includes("|")) {
                const forwardTextOption =
                    resultMap.cmsContent.FunnelFooterWidget.ForwardButtonText.split("|");
                resultMap.cmsContent.FunnelFooterWidget.ForwardButtonText = forwardTextOption[0];
            }

            if (!zip || resultMap.vinByAddress === false) {
                var indexToRemove = resultMap.cmsContent.VinLookupMethod.Answers.findIndex(
                    (answer) => answer.Name === "HomeAddress"
                );
                if (indexToRemove) {
                    resultMap.cmsContent.VinLookupMethod.Answers.splice(indexToRemove, 1);
                }
            }

            vm.setCmsContent(resultMap.cmsContent);
            if (store.getters.externalParameterState?.isExternalParameter) {
                if (store.getters.externalParameterCustomer?.phoneNumber) {
                    await baseMixin.methods.dispatchStoreAction(
                        storeActions.SAVE_PHONE_NUMBER,
                        store.getters.externalParameterCustomer.phoneNumber,
                        false
                    );

                    await baseMixin.methods.dispatchStoreAction(
                        storeActions.SAVE_IS_SMS_OPT_IN,
                        true,
                        false
                    );
                }

                if (store.getters.externalParameterEstimate.vinSelection) {
                    vm.selectedVinLookupMethod = vinPagesMixin.methods.getVinlookupMethod(
                        store.getters.externalParameterEstimate.vinSelection
                    );
                    await nextTick();
                    const isValid = await baseMixin.methods.isFormValid(vm.$refs.theForm);
                    if (isValid) {
                        vm.forwardButtonAction();
                    } else {
                        baseMixin.methods.ResetExternalParamsAndHideModal();
                    }
                } else {
                    baseMixin.methods.ResetExternalParamsAndHideModal();
                }
            } else {
                baseMixin.methods.ResetExternalParamsAndHideModal();
            }
        });
    },
    methods: {
        arePagePrerequisitesValid() {
            return store.getters.damage.isRepair || store.getters.damage.glassToReplace?.length > 0;
        },
        backButtonAction() {
            // route to move backwards
            this.$router.navigateWithoutSaving(
                this.navigationScenarios.CLICKED_BACK,
                this.pageName
            );
        },
        async forwardButtonAction() {
            if (this.selectedVinLookupMethod === vinLookupMethodSelections.MANUALVIN) {
                await this.dispatchStoreAction(storeActions.CLEAR_VIN);
                return this.$router.navigateWithSaving(
                    this.navigationScenarios.SELECTED_MANUAL_VIN,
                    this.pageName
                );
            }
            if (this.selectedVinLookupMethod === vinLookupMethodSelections.LICENSEPLATE) {
                return this.$router.navigateWithSaving(
                    this.navigationScenarios.SELECTED_LICENSE_PLATE,
                    this.pageName
                );
            }
            if (this.selectedVinLookupMethod === vinLookupMethodSelections.HOMEADDRESS) {
                return this.$router.navigateWithSaving(
                    this.navigationScenarios.SELECTED_HOME_ADDRESS,
                    this.pageName
                );
            }
            if (this.selectedVinLookupMethod === vinLookupMethodSelections.DECLINE) {
                return this.$router.navigateWithSaving(
                    this.navigationScenarios.SELECTED_NO_VIN,
                    this.pageName
                );
            }
        },
    },
    computed: {
        questionText() {
            return this.getCmsContent("VinLookupMethod", "QuestionText");
        },
        answersFromCms() {
            return this.getCmsContent("VinLookupMethod", "Answers");
        },
        isRepair() {
            return store.getters.damage.isRepair;
        },
        VinLookupQuestionText() {
            return this.getCmsContent("VinLookupQuestion", "BodyText");
        },
        HeaderText() {
            return this.getCmsContent("VinLookupQuestion", "HeaderText");
        },
        SelectOptionText() {
            return this.getCmsContent("VinLookupQuestion", "FooterText");
        },
        VinLookupQuestionBodyText2() {
            return this.getCmsContent("VinLookupQuestion", "BodyText2");
        },
        VinLookupQuestionFooterText() {
            return this.getCmsContent("VinLookupQuestion", "FooterText");
        },
        VinLookupQuestionFooterText2() {
            return this.getCmsContent("VinLookupQuestion", "FooterText2");
        },
    },
    components: {
        funnelHeader,
        funnelSubHeader,
        navbar,
        buttonQuestion,
        Form,
        loadingModal,
    },
};
</script>

<style lang="scss" scoped>
.header-copy {
    font-family: UrbanistSemibold, Arial, Helvetica, sans-serif;
}
</style>

<style lang="scss">
.vinlookupquestion p {
    font-size: 1.25rem;
}
.header-sub-copy {
    font-size: 0.875rem;
}
.funnel-sub-header {
    padding-bottom: 0;
    h5.dark-header {
        margin-bottom: 1rem;
    }
    .sub-text strong {
        text-transform: uppercase;
        font-weight: 400;
    }
}

.select-an-option {
    font-family: UrbanistSemibold;
    font-weight: 600;
    margin-bottom: 1rem;
}
.select-option {
    font-family: UrbanistSemibold, Arial, Helvetica, sans-serif;
    font-weight: 600;
    color: $black;
}
</style>
