<template>
    <Form @submit="onSubmit" @invalid-submit="onInvalidSubmit" ref="theForm" v-slot="{ meta }">
        <div class="page-container-grouped-styles">
            <funnelHeader cmsWidgetName="FunnelHeaderWidget" />
            <vehicleBanner
                cmsWidgetName="VehicleBannerWidget"
                :displayGenericVehicleImage="false" />
            <funnelSubHeader cmsWidgetName="FunnelSubHeaderWidget" />
            <div class="fade-on-route-transition sub-container make-tall">
                <textBlock
                    cmsWidgetName="paymentServiceOptionsCopy"
                    justifyText="center"
                    typeStyle="small"
                    class="mt-2 mb-5" />
                <cashOrInsuranceQuestion
                    ref="cashOrInsurance"
                    cmsWidgetName="CashOrInsuranceQuestionWidget"
                    v-model="isInsuranceSelected"
                    groupName="CashOrInsuranceQuestion" />
                <servicePackageQuestion
                    ref="servicePackage"
                    cashCmsWidgetName="CashServicePackageQuestionWidget"
                    insuranceCmsWidgetName="InsuranceServicePackageQuestionWidget"
                    v-model="selectedPackage"
                    groupName="ServicePackageQuestion"
                    :availableLineItems="availableLineItems"
                    :isInsuranceSelected="isInsuranceSelected" />
                <textBlock
                    cmsWidgetName="quoteDisclaimer"
                    justifyText="left"
                    typeStyle="caption"
                    class="mt-4" />
                <modal cmsWidgetName="EstimateRainDefenseModal" />
                <modal cmsWidgetName="EstimateFrontWiperModal" />
                <modal cmsWidgetName="EstimateRearWiperModal" />
                <modal cmsWidgetName="EstimateRecalModal" />
                <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 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 { Form } from "vee-validate";

export default {
    name: "quote",
    async beforeRouteEnter(to, from, next) {
        // Call APIs
        const cmsContent = await 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: "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(cmsContent);
            vm.availableLineItems = pricingResults;
            vm.isInsuranceSelected = vm.getDefaultIsInsuranceSelectedValue();
        });
    },
    data() {
        return {
            pricingRequestResult: null,
            isInsuranceSelected: null,
            selectedPackage: null,
            availableLineItems: null,
        };
    },
    methods: {
        arePagePrerequisitesValid() {
            return true;
            //return store.getters.order.damage.isRepair || (store.getters.order.lineItems?.glassParts != null && store.getters.order.lineItems.glassParts.length > 0);
        },
        getDefaultIsInsuranceSelectedValue() {
            const defaultIsInsuranceSelectedValue = this.$store.getters.order.payment.isInsurance;
            if (defaultIsInsuranceSelectedValue != null) {
                return defaultIsInsuranceSelectedValue;
            } else {
                return this.availableLineItems
                    ? baseMixin.methods.getTierOnePackagePrice(this.availableLineItems) > 500
                    : null;
            }
        },
        backButtonAction() {
            vehicleQuestionsMixin.methods.navigateBack(this);
        },
    },
    components: {
        funnelHeader,
        funnelFooter,
        vehicleBanner,
        funnelSubHeader,
        Form,
        textBlock,
        cashOrInsuranceQuestion,
        servicePackageQuestion,
        modal,
    },
};
</script>
