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

                    <techNotes v-model="techNotes" :textAreaLabelCopy="textAreaLabelCopy" />

                    <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";
import techNotes from "@/layouts/customer-details/tech-notes/tech-notes";
//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";

// 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.query.fmgPage);

        // 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;
        },
        backButtonAction() {
            this.$router.navigateWithoutSaving(this.navigationScenarios.CLICKED_BACK, this.$route);
        },
        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 store.getters.applicationUser.saveSessionPromise;
            }

            this.$router.navigateWithSaving(this.navigationScenarios.CLICKED_FORWARD, this.$route);
        },
    },
    components: {
        funnelHeader,
        funnelSubHeader,
        textboxQuestion,
        navbar,
        Form,
        textBlock,
        phoneNumberQuestion,
        checkboxQuestion,
        techNotes,
    },
};
</script>
