<template>
    <Form @submit="onSubmit" @invalid-submit="onInvalidSubmit" ref="theForm" v-slot="{ meta }">
        <loadingModal ref="loadingModal" />
        <div class="container-fluid page-container-grouped-styles">
            <div class="row justify-content-center">
                <div class="col-md-6">
                    <funnelHeader cmsWidgetName="FunnelHeaderWidget" ref="funnelHeader" />
                </div>
            </div>
            <div class="row justify-content-center">
                <div class="col-md-6 col-xl-4">
                    <funnelSubHeader cmsWidgetName="FunnelSubHeaderWidget" class="mt-4" />

                    <div v-if="originalList.length > 0">
                        <insurance-company-question
                            v-model="parentAccountNumber"
                            :originalList="originalList" />
                    </div>
                    <textLink
                        id="payOnMyOwnBackButton"
                        useLoadingModal
                        linkType="text"
                        :text="payWithCashButtonCopy"
                        href="javascript:void(0)"
                        @click-event="backButtonAction((foreceCashSelectionOnQuote = true))" />

                    <navbar
                        cmsWidgetName="FunnelFooterWidget"
                        ref="navbar"
                        :isForwardActionDisabled="!meta.valid || !isParentAccountNumber"
                        @back-clicked="backButtonAction"
                        @ForwardClicked="forwardButtonAction" />
                </div>
            </div>
        </div>
    </Form>
</template>

<script>
// Components
import funnelHeader from "@/fmg-components/funnel-header/funnel-header";
import navbar from "@/fmg-components/nav-bar/nav-bar";
import funnelSubHeader from "@/fmg-components/funnel-sub-header/funnel-sub-header";
import loadingModal from "@/fmg-components/loading-modal/loading-modal.vue";
import insuranceCompanyQuestion from "@/layouts/insurance-company/insurance-company-question";
import textLink from "../../ux-components/text-link/text-link.vue";

// Supporting files
import { fetchCmsContentForPage } from "@/helpers/cms-content-helper";
import { settleAllPromises } from "@/helpers/layout-helper";
import { storeActions } from "@/constants/store-actions";
import { Form, defineRule } from "vee-validate";
import baseMixin from "@/mixins/base-mixin.js";
import { navigateToHeritageFunnel } from "@/helpers/heritage-integration/navigation-helper";
import { applicationConfig } from "@/constants/application-config";
import experimentMixin from "@/mixins/experiment-mixin.js";
import { experimentSettings } from "@/constants/experiments";
import { partNumberStrings } from "@/constants/part-number-strings";
import { deepClone } from "@/helpers/object-helper";
import store from "@/store";

export default {
    name: "insurance-company",
    async beforeRouteEnter(to, from, next) {
        // Remove any Pricing By Day lineItems before going to Heritage insurance
        const isPricingByDayExperiment = experimentMixin.methods.hasSettingEqualTo(
            experimentSettings.PRICING_BY_DAY,
            "true"
        );
        if (isPricingByDayExperiment) {
            const lineItems = deepClone(store.getters.order.lineItems);
            const supportingItemsWithoutPricingByDay =
                baseMixin.methods.filterOutCertainPartTypesOrNumbers(lineItems.supportingItems, {
                    partNumbersToRemove: [partNumberStrings.PRICING_BY_DAY_UPCHARGE],
                });
            baseMixin.methods.dispatchStoreAction(
                storeActions.SAVE_SUPPORTING_ITEMS_SUPPRESSING_STATE_RESETTING,
                supportingItemsWithoutPricingByDay,
                false
            );
        }

        // Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to.query.fmgPage);
        const insuranceCompanyListPromise = baseMixin.methods.dispatchStoreActionWithLogging(
            storeActions.GET_INSURANCE_COMPANY_LIST,
            {},
            "insurance-company"
        );

        // Settle promises and get results
        const promiseResultMap = [
            {
                resultKey: "cmsContent",
                promise: cmsContentPromise,
            },
            {
                resultKey: "insuranceCompanyList",
                promise: insuranceCompanyListPromise,
            },
        ];

        const resultMap = await settleAllPromises(promiseResultMap);

        // Call the "next" function to complete the transition to this page.
        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);
            vm.originalList = resultMap.insuranceCompanyList;
            if (store.getters.externalParameterState?.isExternalParameter) {
                baseMixin.methods.ResetExternalParamsAndHideModal();
            }
        });
    },

    data() {
        return {
            parentAccountNumber: this.parentAccountNumberFromStore(),
            originalList: [],
        };
    },
    computed: {
        isParentAccountNumber() {
            return !!this.parentAccountNumber;
        },
        payWithCashButtonCopy() {
            return this.getCmsContent("PayWithCashWidget", "Text");
        },
    },
    methods: {
        isCashParentAccountNumber() {
            return (
                applicationConfig.CASH_PARENT_ACCOUNT_NUMBER.toString() ===
                store.getters.order?.payment?.parentAccountNumber.toString()
            );
        },
        parentAccountNumberFromStore() {
            const accountNumber = !this.isCashParentAccountNumber()
                ? store.getters.order?.payment?.parentAccountNumber.toString()
                : "";
            return accountNumber;
        },
        arePagePrerequisitesValid() {
            return store.getters.order.payment.isInsurance === true;
        },
        backButtonAction(forceCashSelectionOnQuote) {
            // Go back to Quote page
            if (forceCashSelectionOnQuote) {
                this.$router.navigateWithoutSaving(
                    this.navigationScenarios.CLICKED_BACK,
                    this.$route,
                    { isCashSelected: true }
                );
                return;
            }

            this.$router.navigateWithoutSaving(this.navigationScenarios.CLICKED_BACK, this.$route);
        },
        async forwardButtonAction() {
            // await any pending save-sessions.  if you don't, we will save the new parent account into vuex and then a pending async save-session response overwrites it
            await store.getters.applicationUser.saveSessionPromise;

            await this.dispatchStoreAction(
                this.storeActions.SAVE_PARENT_ACCOUNT_NUMBER,
                this.parentAccountNumber.toString(),
                false
            );

            const billToAccountNumber = await baseMixin.methods.dispatchStoreActionWithLogging(
                storeActions.GET_BILL_TO_ACCOUNT_NUMBER,
                {},
                "insurance-company",
                false
            );

            baseMixin.methods.dispatchStoreAction(
                storeActions.SAVE_BILL_TO_ACCOUNT_NUMBER,
                billToAccountNumber,
                false
            );
            //Reload page when navigate with browser back button
            window.addEventListener("pageshow", this.handlePageShow);

            navigateToHeritageFunnel({
                shouldSaveSession: true,
                pageNameToLog: "insurance-company",
            });
        },
        handlePageShow() {
            window.location.reload();
        },
    },
    unmounted() {
        window.removeEventListener("pageshow", this.handlePageShow);
    },
    components: {
        funnelHeader,
        navbar,
        funnelSubHeader,
        Form,
        loadingModal,
        insuranceCompanyQuestion,
        textLink,
    },
};
</script>

<style lang="scss">
.ui-autocomplete {
    z-index: 3;
}
</style>
