<template>
    <Form @submit="onSubmit" @invalid-submit="onInvalidSubmit" ref="theForm" v-slot="{ meta }">
        <loadingModal ref="loadingModal" />
        <div class="container-fluid page-container-grouped-styles">
            <div class="row justify-content-center">
                <div class="col-md-6">
                    <funnelHeader cmsWidgetName="FunnelHeaderWidget" />
                </div>
            </div>
            <div class="row justify-content-center">
                <div class="col-md-6 col-xl-4">
                    <funnelSubHeader cmsWidgetName="FunnelSubHeaderWidget" class="mt-5" />

                    <serviceZipModalQuestion
                        v-model="serviceZipCodeQuestion"
                        ref="serviceZipCodeQuestion"
                        :mobileFeePart="mobileFeePart"
                        @updated-mobile-fee-part="setMobileFeePart"
                        @updated-serviceability="setServiceabilityDetails"
                        @updated-contains-military-base="setContainsMilitaryBase"
                        linkWidgetName="ServiceZipLinkWidget"
                        modalWidgetName="ServiceZipModalWidget" />

                    <alert
                        ref="alertMilitaryBaseZip"
                        class="my-5"
                        cmsWidgetName="AlertMilitaryBaseZipWidget"
                        v-if="displayMilitaryZipAlert"
                        alertClass="alert-warning" />

                    <alert
                        ref="alertMobileOnly"
                        class="my-5"
                        cmsWidgetName="AlertMobileOnlyWidget"
                        v-if="displayServiceableMobileOnly"
                        alertClass="alert-warning" />

                    <alert
                        ref="alertRecalNoMobile"
                        class="my-5"
                        cmsWidgetName="AlertRecalNoMobileWidget"
                        v-if="displayRecalibrationWarning"
                        @text-link-clicked="openModalAction"
                        alertClass="alert-warning" />

                    <alert
                        ref="alertInshopOnly"
                        class="my-5"
                        cmsWidgetName="AlertInshopOnlyWidget"
                        v-if="displayServiceableInshopOnly"
                        alertClass="alert-warning" />

                    <alert
                        ref="alertNoShops"
                        class="my-5"
                        cmsWidgetName="AlertNoShopsWidget"
                        v-if="displayNoShopsAlert"
                        alertClass="alert-warning" />
                </div>
            </div>
            <div class="row justify-content-center appointment-type">
                <div class="col-md-6">
                    <appointmentTypeQuestion
                        v-model="selectedAppointmentType"
                        v-show="isAppointmentTypeDisplayed"
                        :isServiceableMobile="isServiceableMobile"
                        :isServiceableInshop="isServiceableInshop"
                        :isDisplayed="isAppointmentTypeDisplayed"
                        ref="appointmentTypeQuestion"
                        groupName="appointmentTypeQuestion"
                        cmsWidgetName="AppointmentTypeQuestionWidget"
                        validationRules="option-required" />
                </div>
            </div>
            <div class="row justify-content-center">
                <div class="col-md-6 col-xl-4">
                    <mobileLocationModalQuestions
                        customComponentId="mobileLocationQuestions"
                        v-if="selectedAppointmentType === 'Mobile'"
                        v-model="mobileLocationQuestions"
                        :mobileFeePart="mobileFeePart"
                        @updated-mobile-fee-part="setMobileFeePart"
                        @updated-serviceability="setServiceabilityDetails"
                        @updated-contains-military-base="setContainsMilitaryBase"
                        validationRules="mobile-location-required"
                        ref="mobileLocationQuestions"
                        linkWidgetName="MobileLocationLinkWidget"
                        modalWidgetName="MobileLocationModalWidget" />

                    <shopQuestion
                        ref="shopQuestion"
                        v-show="isShopQuestionDisplayed"
                        v-model="selectedProvider"
                        :selectedAppointmentType="selectedAppointmentType"
                        :shopProviderData="shopProviderData"
                        :isDisplayed="isShopQuestionDisplayed"
                        cmsWidgetName="ShopQuestionWidget" />

                    <contentGroupModal ref="RecalModal" cmsWidgetName="RecalModal" />

                    <navbar
                        cmsWidgetName="FunnelFooterWidget"
                        ref="navbar"
                        :isForwardActionDisabled="!meta.valid || displayNoShopsAlert"
                        @back-clicked="backButtonAction"
                        @ForwardClicked="forwardButtonAction" />
                </div>
            </div>
        </div>
    </Form>
</template>

<script>
// Components
import alert from "@/ux-components/alert/alert";
import serviceZipModalQuestion from "@/layouts/service-location/service-zip-modal-question/service-zip-modal-question";
import mobileLocationModalQuestions from "@/layouts/service-location/mobile-location-modal-questions/mobile-location-modal-questions";
import appointmentTypeQuestion from "@/layouts/service-location/appointment-type-question/appointment-type-question";
import shopQuestion from "@/layouts/service-location/shop-question/shop-question";

import funnelHeader from "@/fmg-components/funnel-header/funnel-header";
import navbar from "@/fmg-components/nav-bar/nav-bar";
import funnelSubHeader from "@/fmg-components/funnel-sub-header/funnel-sub-header";
import loadingModal from "@/fmg-components/loading-modal/loading-modal.vue";
import { Form } from "vee-validate";
import contentGroupModal from "@/fmg-components/content-group-modal/content-group-modal";

// Supporting files
import baseMixin from "@/mixins/base-mixin.js";

import { fetchCmsContentForPage } from "@/helpers/cms-content-helper";
import { settleAllPromises } from "@/helpers/layout-helper";
import {
    getPricedMobileFeePart,
    getServiceabilityDetails,
    getShopProviderData,
} from "@/layouts/service-location/helpers/service-location-helper/service-location-helper";

import { Provider } from "@/layouts/service-location/classes/provider";

import store from "@/store";

// Validation
import { defineRule } from "vee-validate";
import { errorMessages } from "@/constants/error-messages";

const MOBILE_FEE_PART_TYPE = "MOBILE FEE";

// DEFINE VALIDATION RULES
defineRule("mobile-location-required", (value) => {
    if (
        value.addressQuestions.streetAddress == "" ||
        value.addressQuestions.city == "" ||
        value.addressQuestions.state == "" ||
        value.addressQuestions.zipCode == "" ||
        value.isVehicleProtected == null
    ) {
        return errorMessages.MOBILE_LOCATION_REQUIRED;
    }
    return true;
});

export default {
    name: "service-location",
    data() {
        return {
            streetAddress: this.getServiceAddressFromStore(),
            apartmentNumberOrBusinessName: this.getServiceAddress2FromStore(),
            city: this.getServiceCityFromStore(),
            state: this.getServiceStateFromStore(),
            zipCode: this.getServiceZipCodeFromStore(),
            isVehicleProtected: this.getIsVehicleProtectedFromStore(),
            isGlassServiceableInshop: null,
            isRecalibrationServiceableInshop: null,
            isGlassServiceableMobile: null,
            isRecalibrationServiceableMobile: null,
            selectedAppointmentType: this.getSelectedAppointmentType(),
            selectedProvider: this.getSelectedProvider(),
            mobileFeePart: null,
            zipContainsMilitaryBase: false,
            zipCodeCtu: null,
            shopProviderData: null,
        };
    },
    async beforeRouteEnter(to, from, next) {
        // Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to.query.fmgPage);

        const serviceZipCode = store.getters.order.serviceLocation.zipCode;
        const zipCodeDataPromise = baseMixin.methods.getZipCodeData(
            serviceZipCode,
            "service-location"
        );

        const serviceabilityDetailsPromise = getServiceabilityDetails(
            serviceZipCode,
            null,
            "service-location"
        );

        const mobileFeePartPromise = getPricedMobileFeePart(serviceZipCode, "service-location");

        const shopProviderDataPromise = getShopProviderData(serviceZipCode); // shopQuestion.methods.loadInitialData(serviceZipCode);

        // Settle promises and get results
        const promiseResultMap = [
            {
                resultKey: "cmsContent",
                promise: cmsContentPromise,
            },
            {
                resultKey: "zipCodeData",
                promise: zipCodeDataPromise,
            },
            {
                resultKey: "mobileFeePart",
                promise: mobileFeePartPromise,
            },
            {
                resultKey: "serviceabilityDetails",
                promise: serviceabilityDetailsPromise,
            },
            {
                resultKey: "shopProviderData",
                promise: shopProviderDataPromise,
            },
        ];

        const resultMap = await settleAllPromises(promiseResultMap);

        // Call the "next" function to complete the transition to this page.
        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);
            vm.setData(
                resultMap.zipCodeData,
                resultMap.serviceabilityDetails,
                resultMap.mobileFeePart,
                resultMap.shopProviderData
            );
        });
    },
    computed: {
        serviceZipCodeQuestion: {
            get: function () {
                return {
                    state: this.state,
                    zipCode: this.zipCode,
                };
            },
            set: function (newValue) {
                if (newValue.zipCode !== this.zipCode) {
                    this.resetMobileLocation();
                    this.selectedAppointmentType = null;
                    this.selectedProvider = new Provider();
                }

                this.state = newValue.state;
                this.zipCode = newValue.zipCode;

                this.$nextTick();
            },
        },
        mobileLocationQuestions: {
            get: function () {
                return {
                    addressQuestions: {
                        streetAddress: this.streetAddress,
                        apartmentNumberOrBusinessName: this.apartmentNumberOrBusinessName,
                        city: this.city,
                        state: this.state,
                        zipCode: this.zipCode,
                    },
                    isVehicleProtected: this.isVehicleProtected,
                };
            },
            set: function (newValue) {
                if (newValue.addressQuestions.zipCode !== this.zipCode) {
                    getShopProviderData(newValue.addressQuestions.zipCode).then((result) => {
                        this.shopProviderData = result.data;
                        this.selectedProvider = new Provider(
                            this.shopProviderData.mobileProviderNumber
                        );
                    });
                }

                this.setMobileLocation(newValue);
            },
        },
        isServiceableMobile() {
            if (this.isRecalibrationServiceableMobile !== null) {
                return this.isGlassServiceableMobile && this.isRecalibrationServiceableMobile;
            } else {
                return this.isGlassServiceableMobile;
            }
        },
        isServiceableInshop() {
            if (this.isRecalibrationServiceableInshop !== null) {
                return this.isGlassServiceableInshop && this.isRecalibrationServiceableInshop;
            } else {
                return this.isGlassServiceableInshop;
            }
        },
        isShopQuestionDisplayed() {
            return (
                this.selectedAppointmentType === "Inshop" ||
                this.selectedAppointmentType === "Dropoff"
            );
        },
        isAppointmentTypeDisplayed() {
            return this.zipCode && !this.displayNoShopsAlert;
        },
        requiresInshopRecalibration() {
            // Specifically check for isRecalibrationServiceableMobile === false, not null or true.
            return (
                this.isServiceableInshop &&
                this.isGlassServiceableMobile &&
                this.isRecalibrationServiceableMobile === false
            );
        },
        displayRecalibrationWarning() {
            return this.requiresInshopRecalibration;
        },
        displayServiceableInshopOnly() {
            return (
                !this.displayRecalibrationWarning &&
                this.isServiceableInshop &&
                !this.isServiceableMobile
            );
        },
        displayMilitaryZipAlert() {
            return this.zipContainsMilitaryBase && this.isServiceableMobile;
        },
        displayServiceableMobileOnly() {
            return this.isServiceableMobile && !this.isServiceableInshop;
        },
        displayNoShopsAlert() {
            return !this.isServiceableInshop && !this.isServiceableMobile;
        },
        recalibrationInformationModal() {
            return this.$refs.recalibrationInformationModal;
        },
    },
    methods: {
        arePagePrerequisitesValid() {
            return (
                store.getters.lineItems.supportingItems !== null &&
                store.getters.order.serviceLocation.zipCode !== null &&
                store.getters.payment.isInsurance !== null
            );
        },
        setData(zipCodeData, serviceabilityDetails, mobileFeePart, shopProviderData) {
            if (zipCodeData) {
                this.zipContainsMilitaryBase = zipCodeData.containsMilitaryBase;
                this.zipCodeCtu = zipCodeData.zipCodeCtu;
            }

            if (serviceabilityDetails) {
                this.setServiceabilityDetails(serviceabilityDetails);
            }

            if (mobileFeePart) {
                this.mobileFeePart = mobileFeePart;
            }

            if (shopProviderData) {
                this.shopProviderData = shopProviderData;
            }
        },
        setContainsMilitaryBase(val) {
            if (this.zipContainsMilitaryBase !== val) {
                this.zipContainsMilitaryBase = val;
            }
        },
        setMobileFeePart(mobileFeePart) {
            this.mobileFeePart = mobileFeePart;
        },
        getServiceAddressFromStore() {
            return store.getters.order.serviceLocation.address;
        },
        getServiceAddress2FromStore() {
            return store.getters.order.serviceLocation.address2;
        },
        getServiceCityFromStore() {
            return store.getters.order.serviceLocation.city;
        },
        getServiceStateFromStore() {
            return store.getters.order.serviceLocation.state;
        },
        getServiceZipCodeFromStore() {
            return store.getters.order.serviceLocation.zipCode;
        },
        getIsVehicleProtectedFromStore() {
            return store.getters.order.serviceLocation.isVehicleProtected;
        },
        getSelectedAppointmentType() {
            return store.getters.order.serviceLocation.appointmentType;
        },
        getSelectedProvider() {
            return store.getters.order.serviceLocation.provider;
        },
        resetMobileLocation() {
            this.streetAddress = "";
            this.apartmentNumberOrBusinessName = "";
            this.city = "";

            this.isVehicleProtected = null;
        },
        setServiceabilityDetails(serviceabilityDetails) {
            this.isGlassServiceableInshop = serviceabilityDetails.isGlassServiceableInshop;
            this.isRecalibrationServiceableInshop =
                serviceabilityDetails.isRecalibrationServiceableInshop;
            this.isGlassServiceableMobile = serviceabilityDetails.isGlassServiceableMobile;
            this.isRecalibrationServiceableMobile =
                serviceabilityDetails.isRecalibrationServiceableMobile;
        },
        setMobileLocation(mobileLocation) {
            this.streetAddress = mobileLocation.addressQuestions.streetAddress;
            this.apartmentNumberOrBusinessName =
                mobileLocation.addressQuestions.apartmentNumberOrBusinessName;
            this.city = mobileLocation.addressQuestions.city;
            this.state = mobileLocation.addressQuestions.state;
            this.zipCode = mobileLocation.addressQuestions.zipCode;
            this.isVehicleProtected = mobileLocation.isVehicleProtected;
        },
        async reloadShopData(zipCode) {
            await this.$refs.shopQuestion.reloadShopData(zipCode);
        },
        openRecalibrationInformationModal() {
            this.recalibrationInformationModal.openModal();
        },
        backButtonAction() {
            this.$router.navigateWithoutSaving(this.navigationScenarios.CLICKED_BACK, this.$route);
        },
        updateAndSaveSupportingItems() {
            const supportingItems = store.getters.lineItems.supportingItems;
            // if we have a mobile fee, then save/update supporting items
            if (this.selectedAppointmentType == "Mobile") {
                const mobileFeeIndex = supportingItems.findIndex(
                    (item) => item.partType == MOBILE_FEE_PART_TYPE
                );
                // If it already exists, update the price with latest data
                if (mobileFeeIndex >= 0) {
                    supportingItems[mobileFeeIndex].laborAmount = this.mobileFeePart.laborAmount;
                    supportingItems[mobileFeeIndex].sellingPrice = this.mobileFeePart.sellingPrice;
                    supportingItems[mobileFeeIndex].kitPrice = this.mobileFeePart.kitPrice;
                } else {
                    supportingItems.push(this.mobileFeePart);
                }

                this.dispatchStoreAction(
                    this.storeActions.SAVE_SUPPORTING_ITEMS_SUPPRESSING_STATE_RESETTING,
                    supportingItems,
                    false
                );
            } else {
                // if it's not a mobile, then make sure we remove any that may have been added
                const removeMobileFeeIndex = supportingItems.findIndex(
                    (item) => item.partType == MOBILE_FEE_PART_TYPE
                );

                if (removeMobileFeeIndex >= 0) {
                    supportingItems.splice(removeMobileFeeIndex, 1);
                    this.dispatchStoreAction(
                        this.storeActions.SAVE_SUPPORTING_ITEMS_SUPPRESSING_STATE_RESETTING,
                        supportingItems,
                        false
                    );
                }
            }
        },
        async forwardButtonAction() {
            await this.dispatchStoreAction(
                this.storeActions.SAVE_SERVICE_LOCATION,
                {
                    address: this.streetAddress,
                    address2: this.apartmentNumberOrBusinessName,
                    city: this.city,
                    state: this.state,
                    zipCode: this.zipCode,
                    zipCodeCtu: this.zipCodeCtu,
                    appointmentType: this.selectedAppointmentType,
                    isVehicleProtected: this.isVehicleProtected,
                    provider: {
                        providerNumber: this.selectedProvider?.providerNumber,
                        address: {
                            streetAddress: this.selectedProvider?.address?.streetAddress,
                            city: this.selectedProvider?.address?.city,
                            state: this.selectedProvider?.address?.state,
                            zipCode: this.selectedProvider?.address?.zipCode,
                            zipCodeCtu: this.selectedProvider?.address?.zipCodeCtu,
                        },
                    },
                },
                false
            );

            this.updateAndSaveSupportingItems();
            this.$router.navigateWithSaving(this.navigationScenarios.CLICKED_FORWARD, this.$route);
        },
        openModalAction(modalName) {
            this.$refs[modalName].openModal();
        },
    },
    watch: {
        zipCode: {
            handler(newValue) {
                getShopProviderData(this.zipCode).then(async (result) => {
                    this.shopProviderData = result.data;
                    if (this.selectedAppointmentType === "Mobile") {
                        this.selectedProvider = new Provider(
                            this.shopProviderData.mobileProviderNumber
                        );
                    } else {
                        this.selectedProvider = new Provider();
                    }
                });
            },
        },
        selectedAppointmentType: {
            handler(newValue) {
                if (newValue === "Mobile") {
                    this.selectedProvider = new Provider(
                        this.shopProviderData.mobileProviderNumber
                    );
                } else {
                    this.selectedProvider = new Provider();
                }
            },
        },
    },
    components: {
        alert,
        serviceZipModalQuestion,
        appointmentTypeQuestion,
        mobileLocationModalQuestions,
        funnelHeader,
        navbar,
        funnelSubHeader,
        Form,
        loadingModal,
        contentGroupModal,
        shopQuestion,
    },
};
</script>

<style lang="scss">
.appointment-type-question {
    .button-question {
        .col {
            @include media-breakpoint-up(md) {
                padding: 0 0.75rem;
            }
            @include media-breakpoint-up(xl) {
                width: 33.3333333%;
                flex: 0 0 auto;
            }
        }
    }
}
.question-text {
    & > span {
        text-align: center;
        color: $black;
    }
}
</style>
