<template>
    <Form @submit="onSubmit" @invalid-submit="onInvalidSubmit" ref="theForm" v-slot="{ meta }">
        <div class="page-container-grouped-styles quote">
            <loadingModal ref="loadingModal" />
            <funnelHeader cmsWidgetName="FunnelHeaderWidget" />
            <vehicleBanner
                cmsWidgetName="VehicleBannerWidget"
                :displayGenericVehicleImage="false" />
            <funnelSubHeader cmsWidgetName="FunnelSubHeaderWidget" />
            <div class="fade-on-route-transition sub-container make-tall">
                <cashOrInsuranceQuestion
                    ref="cashOrInsurance"
                    cmsWidgetName="CashOrInsuranceQuestionWidget"
                    v-model="isInsuranceSelected"
                    groupName="CashOrInsuranceQuestion" />
                <servicePackageQuestion
                    ref="servicePackage"
                    cashCmsWidgetName="CashServicePackageQuestionWidget"
                    insuranceCmsWidgetName="InsuranceServicePackageQuestionWidget"
                    groupName="ServicePackageQuestion"
                    :availableLineItems="availableLineItems"
                    :isInsuranceSelected="isInsuranceSelected"
                    @vapsItemsSelected="vapsItemsSelectedAction"
                    validationRules="option-required"
                    isRequired />

                <textBlock
                    cmsWidgetName="quoteDisclaimer"
                    justifyText="left"
                    typeStyle="caption"
                    class="mt-4" />
                <modal cmsWidgetName="RainDefenseModal" />
                <modal cmsWidgetName="FrontWiperModal" />
                <modal cmsWidgetName="RearWiperModal" />
                <modal cmsWidgetName="RecalModal" />
                <funnel-footer
                    cmsWidgetName="FunnelFooterWidget"
                    :isForwardActionDisabled="!meta.valid"
                    :isBackButtonHidden="shouldHideBackButton"
                    @back-clicked="backButtonAction"
                    @ForwardClicked="forwardButtonAction" />
            </div>
        </div>
    </Form>
</template>

<script>
// Components
import funnelHeader from "@/common-components/funnel-header/funnel-header";
import funnelFooter from "@/common-components/funnel-footer/funnel-footer";
import vehicleBanner from "@/common-components/vehicle-banner/vehicle-banner";
import funnelSubHeader from "@/common-components/funnel-sub-header/funnel-sub-header";
import cashOrInsuranceQuestion from "./cash-or-insurance-question/cash-or-insurance-question";
import servicePackageQuestion from "./service-package-question/service-package-question";
import textBlock from "@/common-components/text-block/text-block";
import modal from "@/common-components/modal/modal";
import loadingModal from "@/common-components/loading-modal/loading-modal.vue";
import baseMixin from "@/mixins/base-mixin.js";
import vehicleQuestionsMixin from "../../mixins/vehicle-questions-mixin";
import { settleAllPromises } from "@/helpers/layout-helper";
import { storeActions } from "@/constants/store-actions";
import store from "@/store";
import { fetchCmsContentForPage } from "@/helpers/cms-content-helper";
import { required } from "@/helpers/validation-rules";
import { errorMessages } from "@/constants/error-messages";
import { Form, defineRule } from "vee-validate";
import { navigateToHeritageFunnel } from "@/helpers/heritage-integration/navigation-helper";
import { applicationConfig } from "@/constants/application-config";

defineRule("option-required", required(errorMessages.OPTION_REQUIRED));

export default {
    name: "quote",
    async beforeRouteEnter(to, from, next) {
        // Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to.query.fmgPage);
        const wipersPromise = baseMixin.methods.dispatchStoreAction(storeActions.GET_WIPERS);
        const rainDefensePromise = baseMixin.methods.dispatchStoreAction(
            storeActions.GET_RAIN_DEFENSE
        );
        const supportingItemsPromise = baseMixin.methods.dispatchStoreAction(
            storeActions.GET_SUPPORTING_ITEMS
        );

        const promiseResultMap = [
            {
                resultKey: "cmsContent",
                promise: cmsContentPromise,
            },
            {
                resultKey: "wipers",
                promise: wipersPromise,
            },
            {
                resultKey: "rainDefense",
                promise: rainDefensePromise,
            },
            {
                resultKey: "supportingItems",
                promise: supportingItemsPromise,
            },
        ];

        const resultMap = await settleAllPromises(promiseResultMap);
        const glassParts = store.getters.order.lineItems.glassParts ?? [];
        const availableLineItems = [
            resultMap.rainDefense,
            ...resultMap.supportingItems,
            ...resultMap.wipers,
            ...glassParts,
        ];

        const pricingResults = await baseMixin.methods.dispatchStoreAction(
            storeActions.PRICE_ORDER_ITEMS,
            availableLineItems,
            false
        );

        // Call the "next" function to complete the transition to this page.
        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);
            vm.supportingItems = resultMap.supportingItems;
            vm.availableLineItems = pricingResults;
            vm.isInsuranceSelected = vm.getDefaultIsInsuranceSelectedValue(vm.availableLineItems);
        });
    },
    data() {
        return {
            isInsuranceSelected: null,
            selectedVaps: null,
            availableLineItems: null,
            supportingItems: null,
        };
    },
    methods: {
        arePagePrerequisitesValid() {
            return (
                store.getters.order.serviceLocation.zipCode &&
                store.getters.order.serviceLocation.zipCodeCtu &&
                (store.getters.order.damage.isRepair ||
                    (store.getters.order.lineItems?.glassParts != null &&
                        store.getters.order.lineItems.glassParts.length > 0)) &&
                store.getters.order.referralNumber?.length !== 6
            );
        },
        getDefaultIsInsuranceSelectedValue(availableLineItems) {
            // Override if coming back from QuoteDetails. Remove override after Quote release
            const isInsuranceOverrideValue = this.$route.query?.isInsurance;

            const defaultIsInsuranceSelectedValue = this.$store.getters.order.payment.isInsurance;
            if (isInsuranceOverrideValue != null) {
                return isInsuranceOverrideValue == "true";
            } else if (defaultIsInsuranceSelectedValue != null) {
                return defaultIsInsuranceSelectedValue;
            } else {
                return availableLineItems
                    ? baseMixin.methods.getTierOnePackagePrice(
                          baseMixin.methods.filterOutFees(availableLineItems)
                      ) > 500
                    : null;
            }
        },
        vapsItemsSelectedAction(vapsItemsSelected) {
            this.selectedVaps = vapsItemsSelected;
        },
        backButtonAction() {
            vehicleQuestionsMixin.methods.navigateBack(this);
        },
        forwardButtonAction() {
            this.dispatchStoreAction(
                this.storeActions.SAVE_PAYMENT_TYPE,
                this.isInsuranceSelected,
                false
            );
            if (!this.isInsuranceSelected) {
                this.dispatchStoreAction(
                    this.storeActions.SAVE_ACCOUNT_NUMBER,
                    applicationConfig.CASH_ACCOUNT_NUMBER,
                    false
                );
            }
            if (this.$store.getters.order.accountNumber != applicationConfig.CASH_ACCOUNT_NUMBER) {
                this.supportingItems = this.filterOutFees(this.supportingItems);
            }
            this.dispatchStoreAction(
                this.storeActions.SAVE_SUPPORTING_ITEMS,
                this.supportingItems,
                false
            );
            this.dispatchStoreAction(this.storeActions.SAVE_VAPS, this.selectedVaps, false);

            navigateToHeritageFunnel({ loadingModal: this.$refs.loadingModal });
        },
    },
    components: {
        funnelHeader,
        funnelFooter,
        vehicleBanner,
        funnelSubHeader,
        Form,
        textBlock,
        cashOrInsuranceQuestion,
        servicePackageQuestion,
        modal,
        loadingModal,
    },
};
</script>

<style lang="scss">
.quote {
    .funnel-sub-header {
        .sub-text {
            margin-bottom: 24px;
        }
    }
}
</style>
