<template>
    <Form
        ref="theForm"
        v-slot="{ meta }"
        @submit="onSubmit"
        @invalidSubmit="onInvalidSubmit">
        <div class="page-container-grouped-styles">
            <div class="fade-on-route-transition position-relative">
                <siteHeader cmsWidgetName="SiteHeaderWidget" />
                <siteSubHeader
                    id="sub-header"
                    cmsWidgetName="SiteSubHeaderWidget"
                    class="mt-5" />
                <div class="select-car">
                    <div class="container-fluid pb-2">
                        <div class="row px-3">
                            <div class="col">
                                <div class="select-car-form rounded">
                                    <serviceZipModalQuestion
                                        ref="serviceZipCodeQuestion"
                                        v-model="serviceZipCodeQuestion"
                                        modalWidgetName="ServiceZipModalWidget"
                                        @updatedServiceability="setServiceabilityDetails"
                                        @updatedContainsMilitaryBase="setContainsMilitaryBase" />
                                    <alert
                                        v-if="displayMilitaryZipAlert"
                                        ref="alertMilitaryBaseZip"
                                        class="my-5"
                                        cmsWidgetName="AlertMilitaryBaseZipWidget"
                                        alertClass="alert-warning" />
                                    <buttonQuestion
                                        v-model="selectedAppointmentType"
                                        cmsWidgetName="ServiceTypeQuestionWidget"
                                        :questionText="questionText"
                                        :answers="answersFromCms"
                                        buttonTypeString="listCard"
                                        isRequired
                                        validationRules="selection-required"
                                        class="service-location-button-question mb-1" />
                                        <div class="select-car">
                                        <siteFooter
                                            ref="siteFooter"
                                            class="mt-5"
                                            cmsWidgetName="SiteFooterWidget"
                                            :isForwardActionDisabled="!meta.valid"
                                            @backClicked="backButtonAction"
                                            @forwardClicked="forwardButtonAction" />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </Form>
</template>
<script>
// Import Supporting Files
import { fetchCmsContentForPage } from '@/helpers/cms-content-helper';
import { settleAllPromises } from '@/helpers/layout-helper';
import { required } from '@/helpers/validation-rules';
import errorMessages from '@/constants/error-messages';
import buttonQuestion from '@/digital-components/button-question/button-question.vue';
import { useMainStore } from '@/store';
import { getServiceabilityDetails, getZipCodeData } from '@/helpers/service-location-helper';

// Import Component
import alert from '@/ux-components/alert/alert.vue';
import baseFormMixin from '@/mixins/base-form-mixin';
import { Form, defineRule } from 'vee-validate';
import siteFooter from '@/iss-components/site-footer/site-footer.vue';
import siteHeader from '@/iss-components/site-header/site-header.vue';
import siteSubHeader from '@/iss-components/site-sub-header/site-sub-header.vue';
import serviceZipModalQuestion from '@/layouts/service-location/service-zip-modal-question/service-zip-modal-question.vue';

// DEFINE VALIDATION RULES
defineRule('selection-required', required(errorMessages.OPTION_REQUIRED));
export default {
    name: 'service-location',
    components: {
        siteFooter,
        siteHeader,
        siteSubHeader,
        buttonQuestion,
        // eslint-disable-next-line vue/no-reserved-component-names
        Form,
        serviceZipModalQuestion,
        alert
    },
    mixins: [baseFormMixin],
    async beforeRouteEnter(to, from, next) {
        // Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to.query.issPage);

        const serviceZipCode = useMainStore().order.customer.address.zipCode;
        const zipCodeData = getZipCodeData(serviceZipCode);

        const serviceabilityDetailsPromise = getServiceabilityDetails(serviceZipCode);

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

        const resultMap = await settleAllPromises(promiseResultMap);

        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);
            vm.setData(resultMap.zipCodeData,
                resultMap.serviceabilityDetails);
        });
    },
    setup() {
        const mainStore = useMainStore();
        return { mainStore };
    },
    data() {
        return {
            zipCode: this.mainStore.order.customer.address.zipCode,
            state: this.mainStore.order.customer.address.state,
            isServiceZipServiceable: null,
            isGlassServiceableMobile: null,
            isRecalibrationServiceableMobile: null,
            selectedAppointmentType: '',
            zipContainsMilitaryBase: false
        };
    },
    computed: {
        questionText() {
            return this.getCmsContent('ServiceTypeQuestionWidget', 'QuestionText');
        },
        answersFromCms() {
            return this.getCmsContent('ServiceTypeQuestionWidget', 'Answers');
        },
        serviceZipCodeQuestion: {
            get() {
                return {
                    zipCode: this.zipCode,
                    state: this.state
                };
            },
            set(newValue) {
                this.zipCode = newValue.zipCode;
                this.state = newValue.state;

                // TODO: review - this seems like it should be awaited.
                this.$nextTick();
            }
        },
        isServiceableMobile() {
            if (this.isRecalibrationServiceableMobile !== null) {
                return this.isGlassServiceableMobile && this.isRecalibrationServiceableMobile;
            }
            return this.isGlassServiceableMobile;
        },
        displayMilitaryZipAlert() {
            return this.zipContainsMilitaryBase && this.isServiceableMobile;
        }
    },
    methods: {
        arePagePrerequisiteValid() {
            return true;
        },
        backButtonAction() {
            /**
             * this.navigationScenarios comes from base-mixin
             */
            this.$router.navigate(this.navigationScenarios.CLICKED_BACK, this.$route);
        },
        async forwardButtonAction() {
            // validate and save data here
            this.$router.navigate(this.navigationScenarios.CLICKED_FORWARD, this.$route);
        },
        resetDependentState() {

        },
        setData(zipCodeData, serviceabilityDetails) {
            if (zipCodeData) {
                this.zipContainsMilitaryBase = zipCodeData.containsMilitaryBase;
            }
            if (serviceabilityDetails) {
                this.setServiceabilityDetails(serviceabilityDetails);
            }
        },
        setContainsMilitaryBase(val) {
            if (this.zipContainsMilitaryBase !== val) {
                this.zipContainsMilitaryBase = val;
            }
        },
        setServiceabilityDetails(serviceabilityDetails) {
            this.isGlassServiceableInshop = serviceabilityDetails.isGlassServiceableInshop;
            this.isRecalibrationServiceableInshop =
                serviceabilityDetails.isRecalibrationServiceableInshop;
            this.isGlassServiceableMobile = serviceabilityDetails.isGlassServiceableMobile;
            this.isRecalibrationServiceableMobile =
                serviceabilityDetails.isRecalibrationServiceableMobile;
        }
    }
};
</script>

<style lang="scss" scoped>

.page-container-grouped-styles {
    overflow: auto;
}
.modal-open {
    .page-container-grouped-styles {
        overflow: hidden;
    }
}
#sub-header span {
    color: $black;
}
.question-text {
    & > span {
        line-height: 1.5rem;
    }
}
.list-card-content p {
    &:first-of-type {
        line-height: 1.5rem;
    }
    &:not(:nth-of-type(1)){
        line-height: 1.250rem;
    }
}

.choose-option{
    .button-question >div {
        &:first-of-type {
            margin-bottom: 0.95rem;
            line-height: 1.500rem;
        }
    }
}
.button-question{
    .row.form-test-error{
        line-height:1.500rem;
        padding-left: 0rem !important;
    }
}
.service-location-button-question {
    .question-text {
        margin-top: 1.5rem;

        span {
            text-align: center;
        }

    }
}
</style>
