<template>
    <Form
        ref="theForm"
        v-slot="{ meta }"
        @submit="onSubmit"
        @invalidSubmit="onInvalidSubmit">
        <div class="fade-on-route-transition">
            <div class="justify-content-center">
                <siteHeader cmsWidgetName="SiteHeaderWidget" />
            </div>
            <div class="iss-heritage-container-width">
                <div class="policy-holder-details-container iss-heritage-content-container-width">
                    <siteSubHeader
                        id="sub-header"
                        cmsWidgetName="SiteSubHeaderWidget"
                        class="mt-4" />
                    <div class="row">
                        <div class="col">
                            <textboxQuestion
                                ref="policyHolderFirstName"
                                v-model="customerQuestions.firstName"
                                inputId="firstNameField"
                                cmsWidgetName="PolicyholderFirstNameQuestion"
                                isRequired
                                disableAutoFill
                                :validationRules="rules.firstName" />
                        </div>
                        <div class="col">
                            <textboxQuestion
                                ref="policyHolderLastName"
                                v-model="customerQuestions.lastName"
                                inputId="lastNameField"
                                cmsWidgetName="PolicyholderLastNameQuestion"
                                isRequired
                                disableAutoFill
                                :validationRules="rules.lastName" />
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-lg-8">
                            <textboxQuestion
                                ref="phoneNumber"
                                v-model="customerQuestions.phoneNumber"
                                inputId="phoneNumberField"
                                cmsWidgetName="PhoneNumberQuestion"
                                :validationRules="rules.phoneNumber"
                                isRequired
                                :mask="phoneMask"
                                disableAutoFill />
                        </div>
                        <div class="col-lg-4">
                            <textboxQuestion
                                ref="extension"
                                v-model="customerQuestions.extension"
                                inputId="extensionField"
                                cmsWidgetName="ExtensionQuestion"
                                :validationRules="rules.extension"
                                maxLength="5"
                                disableAutoFill />
                        </div>
                    </div>
                    <textboxQuestion
                        ref="email"
                        v-model="customerQuestions.email"
                        inputId="emailField"
                        cmsWidgetName="EmailAddressQuestion"
                        :validationRules="rules.email"
                        isRequired
                        disableAutoFill />
                    <addressQuestions
                        id="address-questions-wrapper"
                        ref="addressQuestions"
                        v-model="customerQuestions.addressQuestions"
                        :includeStreetAddress2="true" />
                    <siteFooter
                        ref="siteFooter"
                        class="mt-5"
                        cmsWidgetName="SiteFooterWidget"
                        :isForwardActionDisabled="!meta.valid"
                        @ForwardClicked="forwardButtonAction"
                        @backClicked="backButtonAction" />
                </div>
            </div>
        </div>
    </Form>
</template>
<script>
// Components
import siteHeader from '@/iss-components/site-header/site-header.vue';
import siteSubHeader from '@/iss-components/site-sub-header/site-sub-header.vue';
import textboxQuestion from '@/digital-components/textbox-question/textbox-question.vue';
import addressQuestions from '@/iss-components/address-questions/address-questions.vue';
import siteFooter from '@/iss-components/site-footer/site-footer.vue';

// Supporting files
import { fetchCmsContentForPage } from '@/helpers/cms-content-helper';
import settleAllPromises from '@/helpers/layout-helper';
import { Form } from 'vee-validate';
import globalRules from '@/constants/global-rules';
import BaseFormMixin from '@/mixins/base-form-mixin.js';
import { useMainStore } from '@/store';

export default {
    name: 'policy-holder-details',
    components: {
        siteHeader,
        siteSubHeader,
        textboxQuestion,
        addressQuestions,
        siteFooter,
        // eslint-disable-next-line vue/no-reserved-component-names
        Form
    },
    mixins: [BaseFormMixin],
    async beforeRouteEnter(to, from, next) {
        // Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to.query.issPage);

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

        // use resultMap to populate layout content.
        const resultMap = await settleAllPromises(promiseResultMap);

        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);
        });
    },
    setup() {
        const mainStore = useMainStore();
        return { mainStore };
    },
    data() {
        return {
            customerQuestions: this.getPolicyHolderDetailsFromStore(),
            rules: {
                firstName: globalRules.POLICYHOLDER_FIRST_NAME_REQUIRED,
                lastName: globalRules.POLICYHOLDER_LAST_NAME_REQUIRED,
                phoneNumber: `${globalRules.PHONE_NUMBER_REQUIRED}|${globalRules.PHONE_NUMBER_FORMAT}`,
                email: `${globalRules.EMAIL_ADDRESS_REQUIRED}|${globalRules.EMAIL_ADDRESS_FORMAT}`,
                extension: `${globalRules.EXTENSION_FORMAT}`,
            }
        };
    },
    computed: {
        isCoverageEnabled() {
            return this.mainStore.issConfig.isCoverageEnabled;
        },
        isPolicyVehicleSelected() {
            return (this.mainStore.order.vehicle.policyVehicleId != null && this.mainStore.order.vehicle.policyVehicleId >= 0);
        }
    },
    methods: {
        async forwardButtonAction() {
            this.mainStore.updatePolicyHolderDetails(this.customerQuestions);
            return this.navigateForward();
        },

        navigateForward() {
            if (this.isPolicyVehicleSelected) {
                this.$router.navigate(
                    this.navigationScenarios.CLICKED_FORWARD_POLICY_VERIFIED,
                    this.$route
                );
            } else {
                this.$router.navigate(
                    this.navigationScenarios.CLICKED_FORWARD_POLICY_UNVERIFIED,
                    this.$route
                );
            }
        },

        backButtonAction() {
            if (this.isPolicyVehicleSelected) {
                this.$router.navigate(
                    this.navigationScenarios.CLICKED_BACK_POLICY_VERIFIED,
                    this.$route
                );
            } else {
                this.$router.navigate(
                    this.navigationScenarios.CLICKED_BACK_POLICY_UNVERIFIED,
                    this.$route
                );
            }
        },

        getPolicyHolderDetailsFromStore() {
            return {
                addressQuestions: {
                    streetAddress:
                        this.mainStore.order.customer.address.streetAddress,
                    streetAddress2:
                        this.mainStore.order.customer.address.streetAddress2,
                    city: this.mainStore.order.customer.address.city,
                    state: this.mainStore.order.customer.address.state,
                    zipCode: this.mainStore.order.customer.address.zipCode
                },
                firstName: this.mainStore.order.customer.firstName,
                lastName: this.mainStore.order.customer.lastName,
                phoneNumber: this.mainStore.order.contactInfo.homePhone,
                extension: this.mainStore.order.contactInfo.extension,
                email: this.mainStore.order.customer.emailAddress
            };
        }
    }
};
</script>

<style lang="scss" scoped>
.iss-heritage-container-width {
    .policy-holder-details-container {
        position: relative;
        min-height: 1px;
        padding-left: .9375rem;
        padding-right: .9375rem;
    }
}

#address-questions-wrapper .alert.heading {
    line-height: 24px;
}

#address-questions-wrapper .form-test-error {
    line-height: 24px;
}
.textbox-question {
    margin-bottom: 1.25rem;
}
.dropdown-question {
    margin-bottom: 1.25rem;
}
</style>
