<template>
    <Form @submit="onSubmit" @invalid-submit="onInvalidSubmit" ref="theForm" v-slot="{ meta }">
        <div class="page-container-grouped-styles position-relative">
            <funnelHeader cmsWidgetName="FunnelHeaderWidget" />
            <div class="select-car">
                <div class="container-fluid pb-2">
                    <div class="row">
                        <div class="col">
                            <div class="select-car-form rounded">
                                <funnelSubHeader
                                    cmsWidgetName="FunnelSubHeaderWidget"
                                    class="siteSubHeader" />

                                <vehicleQuestion
                                    ref="vehicleYearQuestion"
                                    class="mb-2 mt-4"
                                    v-model="selectedYear"
                                    :isDisabled="!yearOptions.length"
                                    :options="yearOptions"
                                    cmsWidgetName="VehicleYearQuestion"
                                    validationRules="year-required"
                                    placeHolderText="Select year"
                                    inputId="yearQuestionField" />

                                <vehicleQuestion
                                    ref="vehicleMakeQuestion"
                                    class="mb-2 mt-4"
                                    v-model="selectedMake"
                                    :isDisabled="!makeOptions.length"
                                    :options="makeOptions"
                                    cmsWidgetName="VehicleMakeQuestion"
                                    v-validate="{ rules: 'required', disabled: !makeOptions.length }"
                                    validationRules="make-required"
                                    placeHolderText="Select make"
                                    inputId="makeQuestionField" />

                                <vehicleQuestion
                                    ref="vehicleModelQuestion"
                                    class="mb-2 mt-4"
                                    v-model="selectedModel"
                                    cmsWidgetName="VehicleModelQuestion"
                                    :isDisabled="!modelOptions.length"
                                    :options="modelOptions"
                                    v-validate="{ rules: 'required', disabled: !modelOptions.length }"
                                    validationRules="model-required"
                                    placeHolderText="Select model"
                                    inputId="modelQuestionField" />

                                <vehicleQuestion
                                    ref="vehicleStyleQuestion"
                                    class="mb-2 mt-4"
                                    v-model="selectedStyle"
                                    cmsWidgetName="VehicleStyleQuestion"
                                    :isDisabled="!styleOptions.length"
                                    :options="styleOptions"
                                    v-validate="{ rules: 'required', disabled: !styleOptions.length }"
                                    validationRules="style-required"
                                    placeHolderText="Select style"
                                    inputId="styleQuestionField" />

                                <vehicleBanner
                                    cmsWidgetName="VehicleBannerWidget"
                                    :displayGenericVehicleImage="displayGeneric"
                                    :displayVehicleImage="imageUrl"
                                    :vehicleCategory="category"
                                    :displayUnmatchedVehicleIcon="unmatchedVehicleIcon"
                                    class="mt-5 mb-3"
                                    ref="banner" />

                                <funnelFooter
                                    cmsWidgetName="FunnelFooterWidget"
                                    @ForwardClicked="forwardButtonAction"
                                    :isForwardActionDisabled="!meta.valid"
                                    ref="funnelFooter" />
                            </div>
                        </div>
                    </div>
                </div>
            </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 funnelSubHeader from "@/fmg-components/funnel-sub-header/funnel-sub-header";
import vehicleBanner from "@/fmg-components/vehicle-banner/vehicle-banner";
import vehicleQuestion from "@/layouts/vehicle/vehicle-question/vehicle-question";

// Supporting files
import { fetchCmsContentForPage } from "@/helpers/cms-content-helper";
import { experimentUniverses } from "@/constants/experiments";
import { getDeviceIdValue, getSessionKeyValue } from "@/helpers/heritage-integration/cookie-helper";
import { settleAllPromises } from "@/helpers/layout-helper";
import { Form, defineRule } from "vee-validate";
import { required } from "@/helpers/validation-rules";
import { errorMessages } from "@/constants/error-messages";
import store from "@/store";
import { storeActions } from "@/constants/store-actions.js";
import baseMixin from "@/mixins/base-mixin.js";

//define validation rules
defineRule("year-required", (value) => {
    if (!value || !value.length ) {
        return errorMessages.YEAR_REQUIRED;
    }
    return true;
});
defineRule("make-required", (value) => {
    if (!value || !value.length) {
        return errorMessages.MAKE_REQUIRED;
    }
    return true;
});
defineRule("model-required", (value) => {
    if (!value || !value.length) {
        return errorMessages.MODEL_REQUIRED;
    }
    return true;
});
defineRule("style-required", (value) => {
    if (!value || !value.length) {
        return errorMessages.STYLE_REQUIRED;
    }
    return true;
});
// defineRule("year-required", required(errorMessages.YEAR_REQUIRED));
// defineRule("make-required", required(errorMessages.MAKE_REQUIRED));
// defineRule("model-required", required(errorMessages.MODEL_REQUIRED));
// defineRule("style-required", required(errorMessages.STYLE_REQUIRED));

export default {
    name: "vehicle",
    data() {
        return {
            selectedYear: this.selectedYearfromStore(),
            selectedMake: this.selectedMakefromStore(),
            selectedModel: this.selectedModelfromStore(),
            selectedStyle: this.selectedStylefromStore(),
            carId: null,
            category: null,
            imageUrl: null,
            imageVifNumber: null,
            imageVifColor: null,
            yearOptions: [],
            makeOptions: [],
            modelOptions: [],
            styleOptions: [],
            displayGeneric: this.displayGenericFromStore(),
            unmatchedVehicleIcon: false,
        };
    },

    async beforeRouteEnter(to, from, next) {
        // Call APIs

        const cmsContentPromise = fetchCmsContentForPage(to.query.fmgPage);
        const experimentForLogging = store.getters.applicationUser.experiments.find(
            (e) => e.universeName === experimentUniverses.CONCEPT_FUNNEL
        );
        const yearQuestionInitialDataPromise = baseMixin.methods.dispatchStoreAction(
            storeActions.GET_VEHICLE_YEARS,
            {}
        );
        var makeQuestionInitialDataPromise = null;
        var modelQuestionInitialDataPromise = null;
        var styleQuestionInitialDataPromise = null;

        if (
            store.getters.order.vehicle.make &&
            store.getters.order.vehicle.model &&
            store.getters.order.vehicle.style
        ) {
            makeQuestionInitialDataPromise = baseMixin.methods.dispatchStoreAction(
                storeActions.GET_VEHICLE_MAKES,
                {
                    year: store.getters.order.vehicle.year,
                }
            );

            modelQuestionInitialDataPromise = baseMixin.methods.dispatchStoreAction(
                storeActions.GET_VEHICLE_MODELS,
                {
                    year: store.getters.order.vehicle.year,
                    make: store.getters.order.vehicle.make,
                }
            );

            styleQuestionInitialDataPromise = baseMixin.methods.dispatchStoreAction(
                storeActions.GET_VEHICLE_STYLES,
                {
                    year: store.getters.order.vehicle.year,
                    make: store.getters.order.vehicle.make,
                    model: store.getters.order.vehicle.model,
                }
            );
        }

        // If the concept funnel experiment is found, as it should be when coming from safelite.com, then log the experiment exposure.
        if (experimentForLogging !== undefined) {
            // Log experiment exposure
            baseMixin.methods.dispatchStoreAction(
                storeActions.LOG_EXPERIMENT_EXPOSURE,
                {
                    userId: getDeviceIdValue(),
                    sessionKey: getSessionKeyValue(),
                    pageName: to.query.fmgPage,
                    experiment: experimentForLogging,
                },
                false
            );
        }

        // Settle promises and get results
        const promiseResultMap = [
            {
                resultKey: "cmsContent",
                promise: cmsContentPromise,
            },
            {
                resultKey: "yearQuestionInitialData",
                promise: yearQuestionInitialDataPromise,
            },
            {
                resultKey: "makeQuestionInitialData",
                promise: makeQuestionInitialDataPromise,
            },
            {
                resultKey: "modelQuestionInitialData",
                promise: modelQuestionInitialDataPromise,
            },
            {
                resultKey: "styleQuestionInitialData",
                promise: styleQuestionInitialDataPromise,
            },
        ];

        let resultMap = await settleAllPromises(promiseResultMap);

        // Call the "next" function to complete the transition to this page.
        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);
            vm.initializeYearComponent(resultMap.yearQuestionInitialData);

            if (
                makeQuestionInitialDataPromise &&
                modelQuestionInitialDataPromise &&
                styleQuestionInitialDataPromise
            )
                vm.initializeMMSComponent(
                    resultMap.makeQuestionInitialData,
                    resultMap.modelQuestionInitialData,
                    resultMap.styleQuestionInitialData
                );
        });
    },

    watch: {
        async selectedYear(year) {
            if (year) {
                const result = await this.getMakeOptions(year);
                this.makeOptions = result?.data;
                if (this.selectedYearfromStore() !== year) {
                    this.selectedMake = null;
                    this.selectedModel = null;
                    this.selectedStyle = null;
                }
            } else {
                this.makeOptions = [];
                this.selectedMake = null;
                this.selectedModel = null;
                this.selectedStyle = null;
            }
        },
        async selectedMake(make) {
            if (make) {
                const result = await this.getModelOptions(this.selectedYear, make);
                this.modelOptions = result?.data;
                if (this.selectedMakefromStore() !== make) {
                    if (this.modelOptions.length === 1) this.selectedModel = this.modelOptions[0];
                    else this.selectedModel = null;
                    this.selectedStyle = null;
                }
            } else {
                this.modelOptions = [];
                this.selectedModel = null;
                this.selectedStyle = null;
            }
        },
        async selectedModel(model) {
            if (model) {
                const result = await this.getStyleOptions(
                    this.selectedYear,
                    this.selectedMake,
                    model
                );
                this.styleOptions = result?.data;
                if (this.selectedModelfromStore() !== model) {
                    if (this.styleOptions.length === 1) this.selectedStyle = this.styleOptions[0];
                    else this.selectedStyle = null;
                }
            } else {
                this.styleOptions = [];
                this.selectedStyle = null;
            }
        },
        async selectedStyle(style) {
            if (style) {
                const result = await this.getVehicle(
                    this.selectedYear,
                    this.selectedMake,
                    this.selectedModel,
                    style
                );
                this.carId = result?.data.carId;
                this.category = result?.data.category;
                this.imageUrl = result?.data.imageUrl;
                this.imageVifNumber = result?.data.imageVifNumber;
                this.imageVifColor = result?.data.imageVifColor;
                if (this.imageUrl == null) {
                    this.displayGeneric = false;
                    this.unmatchedVehicleIcon = true;
                } else this.unmatchedVehicleIcon = false;
            } else {
                this.imageUrl = null;
                this.displayGeneric = true;
            }
        },
    },

    methods: {
        getVehicle(year, make, model, style) {
            return this.dispatchStoreAction(this.storeActions.GET_VEHICLE, {
                year: year,
                make: make,
                model: model,
                style: style,
            });
        },
        displayGenericFromStore() {
            if (store.getters.vehicle.imageUrl !== null) return false;
            else if (
                store.getters.vehicle.imageUrl === null &&
                store.getters.vehicle.carId !== null
            )
                return false;
            else return true;
        },
        arePagePrerequisitesValid() {
            return true;
        },

        async forwardButtonAction() {
            this.dispatchStoreAction(
                storeActions.SAVE_VEHICLE,
                {
                    year: this.selectedYear,
                    make: this.selectedMake,
                    model: this.selectedModel,
                    style: this.selectedStyle,
                    carId: this.carId,
                    category: this.category,
                    imageUrl: this.imageUrl,
                    imageVifNumber: this.imageVifNumber,
                    imageVifColor: this.imageVifColor,
                },
                false
            );
            this.$router.navigateWithSaving(this.navigationScenarios.CLICKED_FORWARD, this.$route);
        },
        initializeYearComponent(initialData) {
            this.yearOptions = initialData;
        },
        initializeMMSComponent(makeOptions, modelOptions, styleOptions) {
            this.makeOptions = makeOptions;
            this.modelOptions = modelOptions;
            this.styleOptions = styleOptions;
        },
        selectedYearfromStore() {
            return store.getters.vehicle.year?.toString();
        },
        selectedMakefromStore() {
            return store.getters.vehicle.make;
        },
        selectedModelfromStore() {
            return store.getters.vehicle.model;
        },
        selectedStylefromStore() {
            return store.getters.vehicle.style;
        },
        async getMakeOptions(year) {
            return await baseMixin.methods.dispatchStoreAction(storeActions.GET_VEHICLE_MAKES, {
                year: year,
            });
        },

        async getModelOptions(year, make) {
            return await baseMixin.methods.dispatchStoreAction(storeActions.GET_VEHICLE_MODELS, {
                year: year,
                make: make,
            });
        },

        async getStyleOptions(year, make, model) {
            return await baseMixin.methods.dispatchStoreAction(storeActions.GET_VEHICLE_STYLES, {
                year: year,
                make: make,
                model: model,
            });
        },
    },

    components: {
        funnelHeader,
        funnelFooter,
        funnelSubHeader,
        vehicleBanner,
        Form,
        vehicleQuestion,
    },
};
</script>

<style lang="scss">
.select-car-form {
    margin-left: 0.75rem;
    margin-right: 0.75rem;
}

.siteSubHeader {
    margin-top: 1.5rem;
}
</style>
