<template>
    <Form
        ref="theForm"
        v-slot="{ meta }"
        @submit="onSubmit"
        @invalidSubmit="onInvalidSubmit">
        <div class="fade-on-route-transition">
            <div class="justify-content-center">
                <siteHeader cmsWidgetName="SiteHeaderWidget" />
            </div>
            <div class="iss-heritage-container-width">
                <div class="vehicle-selection-container iss-heritage-content-container-width">
                    <siteSubHeader
                        cmsWidgetName="SiteSubHeaderWidget"
                        class="mt-4"
                        darkGraySubText />
                    <vehicleQuestion
                        ref="vehicleYearQuestion"
                        v-model="selectedYear"
                        class="mb-1 mt-4"
                        cmsWidgetName="VehicleYearQuestion"
                        :updateValues="updateYearValues"
                        validationRules="year-required"
                        inputId="yearQuestionField" />
                    <vehicleQuestion
                        ref="vehicleMakeQuestion"
                        v-model="selectedMake"
                        class="mb-1 mt-4"
                        cmsWidgetName="VehicleMakeQuestion"
                        :updateValues="updateMakeValues"
                        validationRules="make-required"
                        inputId="makeQuestionField" />
                    <vehicleQuestion
                        ref="vehicleModelQuestion"
                        v-model="selectedModel"
                        class="mb-1 mt-4"
                        cmsWidgetName="VehicleModelQuestion"
                        :updateValues="updateModelValues"
                        validationRules="model-required"
                        inputId="modelQuestionField" />
                    <vehicleQuestion
                        ref="vehicleStyleQuestion"
                        v-model="selectedStyle"
                        class="mb-1 mt-4"
                        cmsWidgetName="VehicleStyleQuestion"
                        :updateValues="updateStyleValues"
                        validationRules="style-required"
                        inputId="styleQuestionField" />
                    <siteFooter
                        ref="siteFooter"
                        class="mt-5"
                        cmsWidgetName="SiteFooterWidget"
                        :isForwardActionDisabled="!meta.valid"
                        @ForwardClicked="forwardButtonAction"
                        @backClicked="navigateBack" />
                </div>
            </div>
        </div>
    </Form>
</template>

<script>
// Components
import siteHeader from '@/iss-components/site-header/site-header.vue';
import siteFooter from '@/iss-components/site-footer/site-footer.vue';
import siteSubHeader from '@/iss-components/site-sub-header/site-sub-header.vue';
import vehicleQuestion from '@/layouts/vehicle-selection/vehicle-question/vehicle-question.vue';
import { useMainStore } from '@/store';

// Supporting files
import baseFormMixin from '@/mixins/base-form-mixin.js';
import { fetchCmsContentForPage } from '@/helpers/cms-content-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 bailoutMessage from '@/constants/bailoutMessage';

// define validation rules
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-selection',
    components: {
        siteHeader,
        siteSubHeader,
        siteFooter,
        Form,
        vehicleQuestion
    },
    mixins: [baseFormMixin],

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

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

        const resultMap = await settleAllPromises(promiseResultMap);

        // Call the "next" function to complete the transition to this page.
        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);
        });
    },
    props: {
        cmsWidgetName: String,
        validationRules: String
    },
    data() {
        const { year, make, model, style } = useMainStore().order.vehicle;
        return {
            selectedYear: year,
            selectedMake: make,
            selectedModel: model,
            selectedStyle: style
        };
    },
    computed: {
    },
    watch: {
        selectedYear(value) {
            this.mainStore.updateVehicleYear(value);
            this.$refs.vehicleMakeQuestion.clearValues();
            if (value) {
                this.$refs.vehicleMakeQuestion.getNewValues();
            }
        },
        selectedMake(value) {
            this.mainStore.updateVehicleMake(value);
            this.$refs.vehicleModelQuestion.clearValues();
            if (value) {
                this.$refs.vehicleModelQuestion.getNewValues();
            }
        },
        selectedModel(value) {
            this.mainStore.updateVehicleModel(value);
            this.$refs.vehicleStyleQuestion.clearValues();
            if (value) {
                this.$refs.vehicleStyleQuestion.getNewValues();
            }
        },
        selectedStyle(value) {
            if (value) {
                this.mainStore.updateVehicleStyle(value);
            }
        }
    },
    mounted() {
        this.$refs.vehicleYearQuestion.getNewValues();
        if (this.selectedYear) {
            this.$refs.vehicleMakeQuestion.getNewValues();
        }
        if (this.selectedMake) {
            this.$refs.vehicleModelQuestion.getNewValues();
        }
        if (this.selectedModel) {
            this.$refs.vehicleStyleQuestion.getNewValues();
        }
    },
    methods: {
        arePagePrerequisitesValid() {
            return true;
        },
        async forwardButtonAction() {
            return this.navigateForward();
        },

        navigateForward() {
            this.mainStore.setVehicle().then((result) => {
                if (!result.data.canSafeliteService) {
                    this.mainStore.setBailout(bailoutMessage.HeavyTruckVehicle(this.mainStore.order.vehicle.carId));
                }

                if (this.mainStore.isBailout) {
                    return this.$router.navigate(
                        this.navigationScenarios.BAILOUT,
                        this.$route
                    );
                }

                return this.$router.navigate(
                    this.navigationScenarios.CLICKED_FORWARD,
                    this.$route
                );
                }
            );
        },
        async updateYearValues() {
            return this.mainStore.getVehicleYears();
        },
        async updateMakeValues() {
            return this.mainStore.getVehicleMakes();
        },
        async updateModelValues() {
            return this.mainStore.getVehicleModels();
        },
        async updateStyleValues() {
            return this.mainStore.getVehicleStyles();
        },
        resetAlert() {
            this.displayNoServiceAlert = false;
        }
    }
};
</script>

<style lang="scss" scoped>
.iss-heritage-container-width {
    .vehicle-selection-container {
        position: relative;
        min-height: 1px;
        padding-left: .9375rem;
        padding-right: .9375rem;
    }
}

.select-car-form {
    margin-left: 0.75rem;
    margin-right: 0.75rem;
}

</style>
