<template>
    <Form @submit="onSubmit" @invalid-submit="onInvalidSubmit" ref="theForm" v-slot="{ meta }">
        <!-- <h3>shopTimeSlots: {{ shopTimeSlots }}</h3> -->
        <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>
            <date-picker
                selectableDatesSetting="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 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 baseMixin from "@/mixins/base-mixin.js";
import { storeActions } from "@/constants/store-actions";
import { settleAllPromises } from "@/helpers/layout-helper";
import { navigateToHeritageFunnel } from "@/helpers/heritage-integration/navigation-helper";
import {
    doesCopyContainRouterLink,
    splitCopyOnCMSPlaceHolder,
    getRouterLinkRouteFromCopy,
    getRouterLinkDisplayTextFromCopy,
} from "@/helpers/cms-content-helper";
import { errorMessages } from "@/constants/error-messages";
import { required } from "@/helpers/validation-rules";

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

export default {
    name: "schedule",
    data() {
        return {
            selectedDate: null,
            mockSelectableDatesData: [
                { dateString: "2023-04-28", year: 2023, month: 4, date: 28 },
                { dateString: "2023-05-04", year: 2023, month: 5, date: 4 },
                { dateString: "2023-05-05", year: 2023, month: 5, date: 5 },
                { dateString: "2023-05-14", year: 2023, month: 5, date: 14 },
                { dateString: "2023-05-21", year: 2023, month: 5, date: 21 },
                { dateString: "2023-05-23", year: 2023, month: 5, date: 23 },
                { dateString: "2023-05-25", year: 2023, month: 5, date: 25 },
                { dateString: "2023-06-11", year: 2023, month: 6, date: 11 },
                { dateString: "2023-06-13", year: 2023, month: 6, date: 13 },
                { dateString: "2023-06-17", year: 2023, month: 6, date: 17 },
            ],
            selectableDatesData: [],
        };
        /*
        shopTimeSlots: { 
            estimatedServiceMinutesMinimum: 120, 
            estimatedServiceMinutesMaximum: 180, 
            days: [ 
                {
                    date: "2023-04-25", 
                    timeSlots: [ 
                        { 
                            id: 12001400, 
                            startTime: "12:00:00Z", 
                            endTime: "14:00:00Z", 
                            offerPremium: false,
                        }, 
                    ], 
                }, 
                { 
                    date: "2023-04-26", 
                    timeSlots: [
                        { id: 12001400, 
                            startTime: "12:00:00Z", 
                            endTime: "14:00:00Z", 
                            offerPremium: false, 
                        },
                        { id: 12001400, 
                            startTime: "14:30:00Z", 
                            endTime: "17:30:00Z", 
                            offerPremium: false, 
                        }
                    ], 
                },
            ],
        }
        */
    },
    async beforeRouteEnter(to, from, next) {
        // Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to.query.fmgPage);

        const getShopTimeSlotsPromise = baseMixin.methods.dispatchStoreAction(
            storeActions.GET_SHOP_TIME_SLOTS,
            {
                startDate: "2023-01-01",
                endDate: "2023-05-01",
                shopAppointmentType: "ZZZZ",
            }
        );

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

        const resultMap = await settleAllPromises(promiseResultMap);

        // Call the "next" function to complete the transition to this page.
        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);
            vm.shopTimeSlots = resultMap.shopTimeSlots;
        });
    },
    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);
        },
    },
    methods: {
        doesCopyContainRouterLink,
        splitCopyOnCMSPlaceHolder,
        getRouterLinkRouteFromCopy,
        getRouterLinkDisplayTextFromCopy,
        arePagePrerequisitesValid() {
            return true;
            // NEED TODO - WHAT ARE PAGE REQ'S FOR THIS PAGE?
        },
        async getAvailableDates(startDate, endDate) {
            // console.log("S- async getAvailableDates");

            // USING DATES PASSED, MAKE AN API CALL
            const newShopTimeSlotsResponse = await baseMixin.methods.dispatchStoreAction(
                storeActions.GET_SHOP_TIME_SLOTS,
                {
                    startDate: startDate,
                    endDate: endDate,
                    shopAppointmentType: "ZZZZ",
                },
                false
            );
            const newShopTimeSlots = newShopTimeSlotsResponse.data;
            // console.log("newShopTimeSlots ", newShopTimeSlots)

            // ADD API CALL RESULTS TO EXISTING DATE DATA
            const currentData = [
                ...this.selectableDatesData,
                this.convertApiResponse(newShopTimeSlots.days),
            ];

            // RETURN ALL THE DATE DATA (THE AGGREGATE)
            return this.mockSelectableDatesData; // TODO REMOVE MOCK DATA
            // return currentData;
        },
        convertApiResponse(responseData) {
            // DATA CONVERSION
            responseData?.forEach((date) => {
                const dateString = date.date;
                date.dateString = dateString;
                const dateStringPieces = dateString.split("-");
                date.year = Number(dateStringPieces[0]);
                date.month = Number(dateStringPieces[1]);
                date.date = Number(dateStringPieces[2]);
            });
            return responseData;
        },
        backButtonAction() {
            this.$router.navigateWithoutSaving(this.navigationScenarios.CLICKED_BACK, this.$route);
        },
        forwardButtonAction() {
            navigateToHeritageFunnel({ loadingModal: this.$refs.loadingModal });
        },
    },
    components: {
        funnelHeader,
        funnelFooter,
        funnelSubHeader,
        Form,
        loadingModal,
        datePicker,
    },
};
</script>

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