<template>
    <Form @submit="onSubmit" @invalid-submit="onInvalidSubmit" ref="theForm" v-slot="{ meta }">
        <div class="page-container-grouped-styles">
            <loadingModal ref="loadingModal" />
            <funnelHeader cmsWidgetName="FunnelHeaderWidget" />
            <funnelSubHeader cmsWidgetName="FunnelSubHeaderWidget" class="mt-5" />
            <div class="text-center mt-1 mb-3" v-if="ChangeShopLink.length">
                <span v-for="copy in ChangeShopLink" :key="copy">
                    <span v-if="doesCopyContainRouterLink(copy)" class="text-body">
                        <router-link
                            :to="{
                                query: { fmgPage: `${getRouterLinkRouteFromCopy(copy)}` },
                                name: 'root',
                            }"
                            >{{ getRouterLinkDisplayTextFromCopy(copy) }}</router-link
                        >
                    </span>
                    <span v-else class="m-0 text-body" v-html="copy"></span>
                </span>
            </div>
            <template v-if="displayWeatherAlert">
                <alert
                    v-for="alert in weatherAlerts"
                    v-show="cmsHeadlineTextFound(alert.cmsWidgetName)"
                    :key="alert.cmsWidgetName"
                    :ref="alert.cmsWidgetName"
                    class="mt-2 mb-3"
                    :cmsWidgetName="alert.cmsWidgetName"
                    alertClass="alert-warning" />
            </template>

            <date-picker
                selectableDates="custom"
                v-model="selectedDate"
                :customSelectableDatesCallback="getAvailableDates" />
            <funnel-footer
                cmsWidgetName="FunnelFooterWidget"
                ref="funnelFooter"
                :isForwardActionDisabled="!meta.valid"
                @back-clicked="backButtonAction"
                @ForwardClicked="forwardButtonAction" />
        </div>
    </Form>
</template>

<script>
// Components
import alert from "@/ux-components/alert/alert";
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 loadingModal from "@/fmg-components/loading-modal/loading-modal.vue";
import { Form, defineRule } from "vee-validate";
import datePicker from "@/digital-components/date-picker/date-picker";

// Supporting files
import { fetchCmsContentForPage } from "@/helpers/cms-content-helper";
import { settleAllPromises } from "@/helpers/layout-helper";
import { navigateToHeritageFunnel } from "@/helpers/heritage-integration/navigation-helper";
import { getAlertReasons } from "@/layouts/schedule/helpers/schedule-helper";
import {
    doesCopyContainRouterLink,
    splitCopyOnCMSPlaceHolder,
    getRouterLinkRouteFromCopy,
    getRouterLinkDisplayTextFromCopy,
} from "@/helpers/cms-content-helper";
import { errorMessages } from "@/constants/error-messages";
import { required } from "@/helpers/validation-rules";
import store from "@/store";

defineRule("date-required", required(errorMessages.DATE_REQUIRED));

export default {
    name: "schedule",
    data() {
        return {
            selectedDate: null,
            weatherAlerts: [],
            mockSelectableDatesData: [
                { year: 2023, month: 4, date: 13 },
                { year: 2023, month: 4, date: 14 },
                { year: 2023, month: 4, date: 26 },
                { year: 2023, month: 5, date: 4 },
                { year: 2023, month: 5, date: 5 },
                { year: 2023, month: 5, date: 14 },
                { year: 2023, month: 5, date: 21 },
                { year: 2023, month: 5, date: 23 },
                { year: 2023, month: 5, date: 25 },
                { year: 2023, month: 6, date: 11 },
            ],
        };
    },
    async beforeRouteEnter(to, from, next) {
        // Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to.query.fmgPage);

        const alertReasonsPromise = getAlertReasons(store.getters.order.serviceLocation.zipCodeCtu);

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

        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.alertReasons);
        });
    },
    computed: {
        ChangeShopLinkText() {
            return this.getCmsContent("ChangeShopLink", "Text");
        },
        ChangeShopLink() {
            // Splits content when brackets are found in text so that text can be looped through and router-link can be injected when needed
            return this.splitCopyOnCMSPlaceHolder(this.ChangeShopLinkText);
        },
        displayWeatherAlert() {
            return this.weatherAlerts.length > 0;
        },
    },
    methods: {
        doesCopyContainRouterLink,
        splitCopyOnCMSPlaceHolder,
        getRouterLinkRouteFromCopy,
        getRouterLinkDisplayTextFromCopy,
        arePagePrerequisitesValid() {
            return true;
            // NEED TODO - WHAT ARE PAGE REQ'S FOR THIS PAGE?
        },
        setData(alertReasonsData) {
            if (alertReasonsData) {
                this.convertReasonsToCmsAlerts(alertReasonsData);
            }
        },
        cmsHeadlineTextFound(widgetName) {
            return this.getCmsContent(widgetName, "HeadlineText") !== "";
        },
        convertReasonsToCmsAlerts(data) {
            this.weatherAlerts = data.reduce((newObj, alert) => {
                newObj.push({
                    cmsWidgetName: `LocationAlert-${alert}`,
                    alertReason: alert,
                });
                return newObj;
            }, []);
        },
        async getWeatherAlertReasons(ctu) {
            await getAlertReasons(ctu)
                .then((response) => {
                    if (response.data) {
                        this.convertReasonsToCmsAlerts(response.data);
                    }
                })
                .catch(() => {
                    console.log("error fetching alert reasons..");
                });
        },
        getAvailableDates(startDate, endDate) {
            return this.mockSelectableDatesData;
        },
        getServiceZipCtuCodeFromStore() {
            return store.getters.order.serviceLocation.zipCodeCtu;
        },
        backButtonAction() {
            this.$router.navigateWithoutSaving(this.navigationScenarios.CLICKED_BACK, this.$route);
        },
        async forwardButtonAction() {
            //TODO: replace properties with real values once they are available
            await this.dispatchStoreAction(
                this.storeActions.SAVE_SCHEDULE,
                {
                    date: "2023-07-04T00:00:00",
                    startTime: "2023-07-04T12:00:00",
                    endTime: "2023-07-04T17:00:00",
                    routeCode: "03341-01820-S-B*20232*11 AM",
                },
                false
            );

            navigateToHeritageFunnel({ loadingModal: this.$refs.loadingModal });
        },
    },
    components: {
        alert,
        funnelHeader,
        funnelFooter,
        funnelSubHeader,
        Form,
        loadingModal,
        datePicker,
    },
    mounted() {},
};
</script>

<style lang="scss"></style>
