<template>
    <Form @submit="onSubmit" @invalid-submit="onInvalidSubmit" ref="theForm" v-slot="{ meta }">
        <funnelHeader cmsWidgetName="FunnelHeaderWidget" ref="funnelHeader" />
        <div class="container page-container-grouped-styles">
            <div class="row">
                <div class="col-12 col-md-10 col-lg-8 col-xl-7">
                    <funnelSubHeader
                        cmsWidgetName="FunnelSubHeaderWidget"
                        class="mt-4 mb-5"
                        alignLeft />
                    <textboxQuestion
                        isRequired
                        class="mb-4"
                        cmsWidgetName="FirstNameWidget"
                        v-model="firstName"
                        ref="firstName"
                        customInputId="firstName"
                        validationRules="first-name-required" />

                    <textboxQuestion
                        isRequired
                        class="mb-4"
                        cmsWidgetName="LastNameWidget"
                        v-model="lastName"
                        ref="lastName"
                        customInputId="lastName"
                        validationRules="last-name-required" />

                    <textboxQuestion
                        isRequired
                        class="mb-4"
                        cmsWidgetName="emailQuestionWidget"
                        v-model="emailAddress"
                        inputId="email"
                        validationRules="email-address-required|email-address-format" />

                    <phoneNumberQuestion
                        isRequired
                        class="mb-4"
                        cmsWidgetName="PhoneNumberQuestionWidget"
                        v-model="phoneNumber"
                        validationRules="phone-number-required" />

                    <checkboxQuestion
                        class="mb-5"
                        cmsWidgetName="TextMeQuestionWidget"
                        v-model="isSmsOptIn" />

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

                    <textBlock
                        class="mb-5"
                        cmsWidgetName="DisclaimerCopyWidget"
                        typeStyle="caption" />
                </div>
            </div>
        </div>
    </Form>
</template>

<script>
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 textboxQuestion from "@/digital-components/textbox-question/textbox-question";
import phoneNumberQuestion from "@/digital-components/phone-number-question/phone-number-question";
import textBlock from "@/digital-components/text-block/text-block";
import checkboxQuestion from "@/digital-components/checkbox-question/checkbox-question";
//Supporting files
import { fetchCmsContentForPage } from "@/helpers/cms-content-helper";
import { settleAllPromises } from "@/helpers/layout-helper";
import { storeActions } from "@/constants/store-actions";
import { errorMessages } from "@/constants/error-messages";
import { required, regex } from "@/helpers/validation-rules";
import { Form, defineRule } from "vee-validate";
import store from "@/store";
import { paymentMethods } from "@/constants/payment-method-constants";
import { flushSaveSessionQueue } from "@/helpers/heritage-integration/order-helper";
import { AppointmentTypeStrings } from "@/constants/schedule-constants";

// DEFINE VALIDATION RULES
defineRule("first-name-required", required(errorMessages.FIRST_NAME_REQUIRED));
defineRule("last-name-required", required(errorMessages.LAST_NAME_REQUIRED));
defineRule("phone-number-required", required(errorMessages.PHONE_REQUIRED));
defineRule("email-address-required", required(errorMessages.EMAIL_ADDRESS_REQUIRED));
defineRule(
    "email-address-format",
    regex(
        /^([a-zA-Z0-9_\-.+]+)@([a-zA-Z0-9-]+)\.([a-zA-Z]{2,})$/,
        errorMessages.EMAIL_ADDRESS_FORMAT
    )
);

export default {
    name: "customer-details",
    async beforeRouteEnter(to, from, next) {
        // Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to.name);

        // 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);
        });
    },
    data() {
        return {
            firstName: this.getFirstNameFromStore(),
            lastName: this.getLastNameFromStore(),
            emailAddress: this.getEmailAddressFromStore(),
            phoneNumber: this.getPhoneNumberFromStore(),
            isSmsOptIn: this.getIsSmsOptInFromStore(),
            techNotes: this.getTechNotesFromStore(),
        };
    },
    computed: {
        textAreaLabelCopy() {
            return this.getCmsContent("TextAreaContentWidget", "QuestionText");
        },
    },
    methods: {
        arePagePrerequisitesValid() {
            return true;
        },
        getFirstNameFromStore() {
            return store.getters.order.customer.firstName;
        },
        getLastNameFromStore() {
            return store.getters.order.customer.lastName;
        },
        getEmailAddressFromStore() {
            return store.getters.order.customer.emailAddress;
        },
        getPhoneNumberFromStore() {
            return store.getters.order.customer.phoneNumber;
        },
        getIsSmsOptInFromStore() {
            return store.getters.order.customer.isSmsOptIn;
        },
        getTechNotesFromStore() {
            return store.getters.order.serviceLocation.techNotes;
        },
        getSelectedAppointmentType() {
            return store.getters.order.serviceLocation.appointmentType;
        },
        backButtonAction() {
            if (this.getSelectedAppointmentType() == AppointmentTypeStrings.MOBILE) {
                this.$router.navigateWithoutSaving(
                    this.navigationScenarios.CLICKED_BACK_WITH_MOBILE_SERVICE,
                    this.pageName
                );
            } else {
                this.$router.navigateWithoutSaving(
                    this.navigationScenarios.CLICKED_BACK,
                    this.pageName
                );
            }
        },
        async forwardButtonAction() {
            this.dispatchStoreAction(
                this.storeActions.SAVE_CUSTOMER_DETAILS,
                {
                    firstName: this.firstName,
                    lastName: this.lastName,
                    emailAddress: this.emailAddress,
                    phoneNumber: this.phoneNumber,
                    isSmsOptIn: this.isSmsOptIn,
                },
                false
            );

            this.dispatchStoreAction(
                this.storeActions.SAVE_SERVICE_LOCATION_TECH_NOTES,
                this.techNotes,
                false
            );

            // if the user has resorted to using browser back/forward buttons we could have promises unresolved if they clicked back before pia work order submission.
            // so attempt to wait for them to finish.
            if (store.getters.order.payment.isPia) {
                this.dispatchStoreAction(
                    storeActions.SAVE_PAYMENT_METHOD_CHOICE,
                    paymentMethods.NONE,
                    false
                );
                await flushSaveSessionQueue();
            }

            this.$router.navigateWithSaving(
                this.navigationScenarios.CLICKED_FORWARD,
                this.pageName
            );
        },
    },
    components: {
        funnelHeader,
        funnelSubHeader,
        textboxQuestion,
        navbar,
        Form,
        textBlock,
        phoneNumberQuestion,
        checkboxQuestion,
    },
};
</script>
<style lang="scss">
.form-check {
    margin-bottom: 0.5rem;
}
</style>
