<template>
    <Form @submit="onSubmit" @invalid-submit="onInvalidSubmit" ref="theForm" v-slot="{ meta }">
        <div class="page-container-grouped-styles">
            <loadingModal ref="loadingModal" />
            <funnelHeader cmsWidgetName="FunnelHeaderWidget" />
            <vehicleBanner cmsWidgetName="VehicleBannerWidget" />
            <funnelSubHeader class="pb-4" cmsWidgetName="FunnelSubHeaderWidget" />
            <div class="fade-on-route-transition sub-container make-tall">
                <div v-if="!skipVin">
                    <div class="vinlookupquestion" v-html="this.VinLookupQuestionText"></div>
                    <buttonQuestion
                        cmsWidgetName="VinLookupMethod"
                        :answers="answersFromCms"
                        groupName="vinLookupMethodOption"
                        buttonTypeString="listButton"
                        v-model="selectedVinLookupMethod"
                        isRequired
                        validationRules="option-required"
                        :logDisplayedValuesEvent="true" />
                </div>
                <div v-else>
                    <alert
                        class="my-4"
                        :cmsWidgetName="alertInfo"
                        alertClass="alert-info"
                        v-bind:isDismissible="false" />
                    <div class="row my-2">
                        <div class="col">
                            <textboxQuestion
                                cmsWidgetName="ServiceZipQuestionWidget"
                                v-model="serviceZipCode"
                                inputId="serviceZipCode"
                                mask="#####"
                                isRequired
                                validationRules="zip-required|zip-format" />
                        </div>
                    </div>
                    <div class="row mt-2">
                        <div class="col">
                            <textboxQuestion
                                cmsWidgetName="EmailAddressQuestionWidget"
                                v-model="emailAddress"
                                inputId="emailAddress"
                                isRequired
                                disableAutoFill
                                validationRules="email-address-required|email-address-format" />
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col">
                            <textBlock
                                cmsWidgetName="QuoteEmailTextBlockWidget"
                                typeStyle="caption" />
                        </div>
                    </div>
                    <alert
                        ref="alertInvalidZip"
                        v-if="displayInvalidZipAlert"
                        class="my-4"
                        cmsWidgetName="AlertInvalidZipWidget"
                        alertClass="alert-danger"
                        v-bind:isDismissible="false" />
                    <alert
                        class="my-4"
                        :manualHeadline="AlertNonServiceableZipHeader"
                        :manualCopy="AlertNonServiceableZipBody"
                        v-model="customAlertData"
                        v-if="displayNonServiceableZipAlert"
                        alertClass="alert-danger" />
                </div>
                <funnel-footer
                    cmsWidgetName="FunnelFooterWidget"
                    ref="funnelFooter"
                    :isForwardActionDisabled="!meta.valid"
                    @back-clicked="backButtonAction"
                    @ForwardClicked="forwardButtonAction" />
            </div>
        </div>
    </Form>
</template>

<script>
// Components
import funnelHeader from "@/fmg-components/funnel-header/funnel-header";
import funnelFooter from "@/fmg-components/funnel-footer/funnel-footer";
import vehicleBanner from "@/fmg-components/vehicle-banner/vehicle-banner";
import funnelSubHeader from "@/fmg-components/funnel-sub-header/funnel-sub-header";
import buttonQuestion from "@/digital-components/button-question/button-question";
import alert from "@/ux-components/alert/alert";
import textboxQuestion from "@/digital-components/textbox-question/textbox-question";
import textBlock from "@/digital-components/text-block/text-block";
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 experimentMixin from "@/mixins/experiment-mixin";
import { experimentSettings } from "@/constants/experiments";
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";

// 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,
            serviceZipCode: this.getZipFromStore() ?? this.$route.query.zipcode,
            emailAddress: this.getEmailFromStore(),
            displayInvalidZipAlert: false,
            displayNonServiceableZipAlert: false,
            skipVin: false,
            skipVinNotRepair: false,
        };
    },

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

        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 = lowerCaseParams.get(queryStrings.ZIP_CODE)
            ? lowerCaseParams.get(queryStrings.ZIP_CODE)
            : store.getters.order.serviceLocation.zipCode;

        var vinByAddressPromise;
        if (zip) {
            vinByAddressPromise = baseMixin.methods.dispatchStoreAction(
                storeActions.IS_VIN_BY_ADDRESS_PERMISSIBLE,
                zip,
                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);
        const skipVin = await skipVinLookup();
        const skipVinNotRepair = await skipVinLookupNotRepair();

        next((vm) => {
            vm.skipVin = skipVin;
            vm.skipVinNotRepair = skipVinNotRepair;
            if (resultMap.cmsContent.FunnelFooterWidget.ForwardButtonText.includes("|")) {
                const forwardTextOption =
                    resultMap.cmsContent.FunnelFooterWidget.ForwardButtonText.split("|");
                if (skipVin) {
                    resultMap.cmsContent.FunnelFooterWidget.ForwardButtonText =
                        forwardTextOption[1];
                } else {
                    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);
        });
    },
    methods: {
        getZipFromStore() {
            return store.getters.order.serviceLocation.zipCode;
        },
        getEmailFromStore() {
            return store.getters.order.customer.emailAddress;
        },
        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.$route);
        },
        async forwardButtonAction() {
            if (this.skipVin) {
                const zipCodeData = await this.getZipCodeData(this.serviceZipCode);
                await this.dispatchStoreAction(storeActions.SAVE_EMAIL, this.emailAddress, false);
                await this.dispatchStoreAction(
                    storeActions.SAVE_SERVICE_ZIP_CODE_INFO,
                    {
                        zipCode: this.serviceZipCode,
                        state: zipCodeData.state,
                        zipCodeCtu: zipCodeData.zipCodeCtu,
                    },
                    false
                );

                if (!zipCodeData.isValid) {
                    this.displayInvalidZipAlert = true;
                    return this.$refs.funnelFooter.removeLoader();
                }
                this.displayInvalidZipAlert = false;

                if (!zipCodeData.isServiceable) {
                    this.displayNonServiceableZipAlert = true;
                    return this.$refs.funnelFooter.removeLoader();
                }
                this.displayNonServiceableZipAlert = false;

                const payment = this.$store.getters.payment;
                const vehicleChangedDuringPolicyLookupInHeritage =
                    payment.isInsurance && payment.insuranceCoverage.coverageStatus;
                if (vehicleChangedDuringPolicyLookupInHeritage) {
                    navigateToHeritageFunnel({ loadingModal: this.$refs.loadingModal });
                } else if (this.$store.getters.order.referralNumber?.length === 6) {
                    await this.navigateForwardWithSingleCarMatch();
                } else if (this.isRepair) {
                    const supportingItemsPromise = await this.dispatchStoreAction(
                        storeActions.GET_SUPPORTING_ITEMS
                    );

                    const promiseResultMap = [
                        {
                            resultKey: "supportingItems",
                            promise: supportingItemsPromise,
                        },
                    ];

                    const resultMap = await settleAllPromises(promiseResultMap);

                    this.dispatchStoreAction(
                        this.storeActions.SAVE_SUPPORTING_ITEMS,
                        resultMap.supportingItems,
                        false
                    );

                    // call saveSession here - navigateWithSaving saves too late in the flow
                    await saveSession({});
                    return this.$router.navigateWithSaving(
                        this.navigationScenarios.CLICKED_FORWARD_WITH_NO_QUESTIONS,
                        this.$route
                    );
                } else {
                    // if we're skipping the vin-lookup but it's not a repair, we still need to get the parts
                    await this.navigateForwardWithSingleCarMatch();
                }
            }

            if (this.selectedVinLookupMethod === vinLookupMethodSelections.MANUALVIN) {
                await this.dispatchStoreAction(storeActions.CLEAR_VIN);
                return this.$router.navigateWithSaving(
                    this.navigationScenarios.SELECTED_MANUAL_VIN,
                    this.$route
                );
            }
            if (this.selectedVinLookupMethod === vinLookupMethodSelections.LICENSEPLATE) {
                return this.$router.navigateWithSaving(
                    this.navigationScenarios.SELECTED_LICENSE_PLATE,
                    this.$route
                );
            }
            if (this.selectedVinLookupMethod === vinLookupMethodSelections.HOMEADDRESS) {
                return this.$router.navigateWithSaving(
                    this.navigationScenarios.SELECTED_HOME_ADDRESS,
                    this.$route
                );
            }
        },
    },
    computed: {
        AlertNonServiceableZipHeader() {
            return this.getCmsContent("AlertNonServiceableZipWidget", "HeadlineText").replaceAll(
                "{custom:serviceZip}",
                this.serviceZipCode
            );
        },
        AlertNonServiceableZipBody() {
            return this.getCmsContent("AlertNonServiceableZipWidget", "BodyText");
        },
        questionText() {
            return this.getCmsContent("VinLookupMethod", "QuestionText");
        },
        answersFromCms() {
            return this.getCmsContent("VinLookupMethod", "Answers");
        },
        isRepair() {
            return store.getters.damage.isRepair;
        },
        alertInfo() {
            return this.skipVinNotRepair ? "AlertQuoteVinOptional" : "AlertQuoteReady";
        },
        VinLookupQuestionText() {
            return this.getCmsContent("VinLookupQuestion", "BodyText");
        },
    },
    watch: {
        serviceZipCode() {
            this.displayNonServiceableZipAlert = false;
        },
    },
    components: {
        funnelHeader,
        vehicleBanner,
        funnelSubHeader,
        funnelFooter,
        buttonQuestion,
        Form,
        alert,
        textboxQuestion,
        textBlock,
        loadingModal,
    },
};
</script>

<style lang="scss">
.vinlookupquestion p {
    margin-bottom: 0;
}
.vinlookupquestion p:nth-child(2) {
    font-size: 0.875rem;
    margin-bottom: 1rem;
}
</style>
