<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" />
                    <alert
                        v-if="displayNoServiceAlert"
                        ref="AlertNoService"
                        class="mt-5"
                        cmsWidgetName="AlertVehicleSelection"
                        alertClass="alert-danger"
                        :isDismissable="false" />
                    <siteFooter
                        ref="siteFooter"
                        class="mt-5"
                        cmsWidgetName="SiteFooterWidget"
                        :isForwardActionDisabled="!meta.valid || displayNoServiceAlert"
                        @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 alert from '@/ux-components/alert/alert.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,
        // eslint-disable-next-line vue/no-reserved-component-names
        Form,
        vehicleQuestion,
        alert
    },
    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,
            displayNoServiceAlert: false
        };
    },
    computed: {
    },
    watch: {
        selectedYear(value) {
            this.resetAlert();
            this.mainStore.updateVehicleYear(value);
            this.$refs.vehicleMakeQuestion.clearValues();
            if (value) {
                this.$refs.vehicleMakeQuestion.getNewValues();
            }
        },
        selectedMake(value) {
            this.resetAlert();
            this.mainStore.updateVehicleMake(value);
            this.$refs.vehicleModelQuestion.clearValues();
            if (value) {
                this.$refs.vehicleModelQuestion.getNewValues();
            }
        },
        selectedModel(value) {
            this.resetAlert();
            this.mainStore.updateVehicleModel(value);
            this.$refs.vehicleStyleQuestion.clearValues();
            if (value) {
                this.$refs.vehicleStyleQuestion.getNewValues();
            }
        },
        selectedStyle(value) {
            this.resetAlert();
            this.mainStore.updateVehicleStyle(value);
            this.mainStore.setVehicle(
                this.selectedYear,
                this.selectedMake,
                this.selectedModel,
                this.selectedStyle
            ).then((result) => {
                this.displayNoServiceAlert = !result.data.canSafeliteService;
            });
        }
    },
    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();
        }
        if (this.selectedStyle) {
            this.mainStore.setVehicle(
                this.selectedYear,
                this.selectedMake,
                this.selectedModel,
                this.selectedStyle
            ).then((result) => {
                this.displayNoServiceAlert = !result.data.canSafeliteService;
            });
        }
    },
    methods: {
        arePagePrerequisitesValid() {
            return true;
        },
        async forwardButtonAction() {
            return this.navigateForward();
        },

        navigateForward() {
            this.mainStore.setVehicle().then(
                () => {
                    if (this.mainStore.isBailout) {
                        this.$router.navigate(
                            this.navigationScenarios.CLICKED_FORWARD_WITH_BAILOUT,
                            this.$route
                        );
                        return;
                    }

                    this.$router.navigate(
                        this.navigationScenarios.CLICKED_FORWARD,
                        this.$route
                    );
                },
                (error) => {
                    // eslint-disable-next-line max-len
                    this.mainStore.setBailout(bailoutMessage.vehicleYMMSLookupError(this.mainStore.vehicle.year, this.mainStore.vehicle.make, this.mainStore.vehicle.model, this.mainStore.vehicle.style, error));
                    this.$router.navigate(
                        this.navigationScenarios.CLICKED_FORWARD_WITH_BAILOUT,
                        this.$route
                    );
                }
            );
        },
        async updateYearValues() {
            return this.mainStore.getVehicleYears().then(
                (response) => response,
                (error) => {
                    this.mainStore.setBailout(bailoutMessage.vehicleYMMSLookupError(null, null, null, null, error));
                    this.$router.navigate(
                        this.navigationScenarios.CLICKED_FORWARD_WITH_BAILOUT,
                        this.$route
                    );
                }
            );
        },
        async updateMakeValues() {
            return this.mainStore.getVehicleMakes().then(
                (response) => response,
                (error) => {
                    this.mainStore.setBailout(bailoutMessage.vehicleYMMSLookupError(this.mainStore.vehicle.year, null, null, null, error));
                    this.$router.navigate(
                        this.navigationScenarios.CLICKED_FORWARD_WITH_BAILOUT,
                        this.$route
                    );
                }
            );
        },
        async updateModelValues() {
            return this.mainStore.getVehicleModels().then(
                (response) => response,
                (error) => {
                    // eslint-disable-next-line max-len
                    this.mainStore.setBailout(bailoutMessage.vehicleYMMSLookupError(this.mainStore.vehicle.year, this.mainStore.vehicle.make, null, null, error));
                    this.$router.navigate(
                        this.navigationScenarios.CLICKED_FORWARD_WITH_BAILOUT,
                        this.$route
                    );
                }
            );
        },
        async updateStyleValues() {
            return this.mainStore.getVehicleStyles().then(
                (response) => response,
                (error) => {
                    // eslint-disable-next-line max-len
                    this.mainStore.setBailout(bailoutMessage.vehicleYMMSLookupError(this.mainStore.vehicle.year, this.mainStore.vehicle.make, this.mainStore.vehicle.model, null, error));
                    this.$router.navigate(
                        this.navigationScenarios.CLICKED_FORWARD_WITH_BAILOUT,
                        this.$route
                    );
                }
            );
        },
        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>
