<template>
    <Form
        ref="theForm"
        v-slot="{ meta }"
        @submit="onSubmit"
        @invalidSubmit="onInvalidSubmit">
        <div class="page-container-grouped-styles welcome">
            <div class="fade-on-route-transition position-relative">
                <siteHeader cmsWidgetName="SiteHeaderWidget" />
                <siteSubHeader
                    cmsWidgetName="SiteSubHeaderWidget"
                    class="mt-4" />
                <div class="container-fluid px-5">
                    <div class="row mt-5">
                        <div class="col">
                            <textboxQuestion
                                ref="policyNumber"
                                v-model="welcomePageModel.policyNumber"
                                inputId="policyNumberField"
                                cmsWidgetName="PolicyNumberQuestion"
                                isRequired
                                disableAutoFill
                                :isDisabled="isPolicyHolderEnabled"
                                :validationRules="rules.policyNumber" />
                        </div>
                    </div>
                    <div
                        v-if="isCoverageEnabled"
                        class="row mt-4">
                        <div class="col">
                            <textboxQuestion
                                ref="policyZip"
                                v-model="welcomePageModel.policyZipCode"
                                inputId="policyZipCode"
                                cmsWidgetName="PolicyZipQuestion"
                                isRequired
                                :validationRules="rules.policyZip" />
                        </div>
                    </div>
                    <div class="row mt-4">
                        <div class="col">
                            <textboxQuestion
                                ref="dateOfLoss"
                                v-model="welcomePageModel.dateOfLoss"
                                type="date"
                                cmsWidgetName="DateOfLossQuestion"
                                inputId="dateOfLossField"
                                isRequired
                                disableAutoFill
                                :max="new Date().toJSON().slice(0, 10)"
                                :min="'1972-12-01'"
                                :validationRules="rules.lossDate" />
                        </div>
                    </div>
                    <div class="row px-4">
                        <div class="col px-0">
                            <textBlock
                                cmsWidgetName="DamageDateEstimateWidget"
                                typeStyle="small"
                                class="mt-2" />
                        </div>
                    </div>
                    <div class="row mt-4">
                        <div class="col">
                            <dropdownQuestion
                                id="welcomeDropdown"
                                ref="damageCause"
                                v-model="welcomePageModel.damageCause"
                                cmsWidgetName="DamageCauseQuestion"
                                inputId="damageCauseQuestionField"
                                :options="DamageCauseOptions"
                                disableAutoFill
                                :validationRules="rules.damageOption"
                                placeHolderText="Select an option" />
                        </div>
                    </div>
                    <div class="row mt-4">
                        <div class="col">
                            <textboxQuestion
                                ref="phoneNumber"
                                v-model="welcomePageModel.phoneNumber"
                                inputId="phoneNumberField"
                                cmsWidgetName="PhoneNumberQuestion"
                                :validationRules="rules.phoneNumber"
                                isRequired
                                mask="###-###-####"
                                disableAutoFill />
                        </div>
                    </div>
                    <div class="row mt-4">
                        <div class="col">
                            <textboxQuestion
                                ref="email"
                                v-model="welcomePageModel.email"
                                inputId="emailField"
                                cmsWidgetName="EmailAddressQuestion"
                                :validationRules="rules.email"
                                isRequired
                                disableAutoFill />
                        </div>
                    </div>
                    <div class="row">
                        <div class="col">
                            <textboxQuestion
                                v-if="displayDamageCityQuestion"
                                ref="damageCity"
                                v-model="welcomePageModel.damageCity"
                                class="mt-4"
                                inputId="damageCityField"
                                cmsWidgetName="DamageCityQuestion"
                                isRequired
                                disableAutoFill
                                :validationRules="rules.lossCity" />
                        </div>
                    </div>
                    <div class="row">
                        <div class="col">
                            <dropdownQuestion
                                v-if="displayDamageStateQuestion"
                                id="welcomeDropdown"
                                ref="state"
                                v-model="welcomePageModel.damageState"
                                class="mt-4"
                                cmsWidgetName="DamageStateQuestion"
                                inputId="8fdf9dc2e13e430eb57529499dceb3eb"
                                :options="getStates"
                                :validationRules="rules.lossState"
                                isRequired
                                disableAutoFill
                                placeHolderText="Select an option" />
                        </div>
                    </div>
                    <div class="row mb-3">
                        <buttonQuestion
                            v-if="displayGlassOnlyQuestion"
                            ref="glassOnlyDamage"
                            v-model="welcomePageModel.isDamageGlassOnly"
                            class="px-0 mt-4"
                            cmsWidgetName="GlassOnlyQuestion"
                            inputId="isDamageGlassOnly"
                            :answers="DamageGlassOnlyOptions"
                            :questionText="DamageGlassOnlyQuestion"
                            buttonTypeString="listButtonHorizontal"
                            :validationRules="rules.damageOption"
                            isRequired
                            isSmallQuestionLabelText
                            disableAutoFill />
                    </div>
                    <div
                        id="welcomeFooter"
                        class="row position-sticky top-100">
                        <div class="col">
                            <siteFooter
                                class="mt-3"
                                cmsWidgetName="SiteFooterWidget"
                                :isForwardActionDisabled="!meta.valid"
                                @backClicked="backButtonAction"
                                @ForwardClicked="forwardButtonAction" />
                        </div>
                    </div>
                </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 siteFooter from '@/iss-components/site-footer/site-footer.vue';
import textboxQuestion from '@/digital-components/textbox-question/textbox-question.vue';
import buttonQuestion from '@/digital-components/button-question/button-question.vue';
import dropdownQuestion from '@/digital-components/dropdown-question/dropdown-question.vue';
import textBlock from '@/digital-components/text-block/text-block.vue';

// Supporting files
import { fetchCmsContentForPage } from '@/helpers/cms-content-helper';
import settleAllPromises from '@/helpers/layout-helper';
import { Form, defineRule } from 'vee-validate';
import { required, regex } from '@/helpers/validation-rules';
import errorMessages from '@/constants/error-messages';
import BaseFormMixin from '@/mixins/base-form-mixin.js';
import { useMainStore } from '@/store';
import states from '@/constants/states';
import globalRules from '@/constants/global-rules';

// define validation rules
defineRule('loss-date-required', required(errorMessages.LOSS_DATE_REQUIRED));
defineRule('policy-number-required', required(errorMessages.POLICY_NUMBER_REQUIRED));
defineRule('loss-state-required', required(errorMessages.LOSS_STATE_REQUIRED));
defineRule('loss-city-required', required(errorMessages.LOSS_CITY_REQUIRED));
defineRule('damage-option-required', required(errorMessages.DAMAGE_OPTION_REQUIRED));
defineRule('policy-zip-required', required(errorMessages.POLICY_ZIP_REQUIRED));
defineRule(
    'policy-zip-format',
    regex(/(^\d{5}$)|(^\d{5}-\d{4}$)/, errorMessages.POLICY_ZIP_FORMAT)
);

export default {
    name: 'welcome-page',
    components: {
        siteHeader,
        siteSubHeader,
        buttonQuestion,
        textboxQuestion,
        dropdownQuestion,
        siteFooter,
        textBlock,
        // 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();

        // Set order account number from the issConfig.
        mainStore.order.accountNumber = mainStore.issConfig.accountNumber;

        return { mainStore };
    },
    data() {
        return {
            welcomePageModel: this.getWelcomePageModelFromStore(),
            vehiclesFound: [],
            rules: {
                policyNumber: 'policy-number-required',
                policyZip: 'policy-zip-required|policy-zip-format',
                lossDate: 'loss-date-required',
                damageOption: 'damage-option-required',
                phoneNumber: `${globalRules.PHONE_NUMBER_REQUIRED}|${globalRules.PHONE_NUMBER_FORMAT}`,
                email: `${globalRules.EMAIL_ADDRESS_REQUIRED}|${globalRules.EMAIL_ADDRESS_FORMAT}`,
                lossCity: 'loss-city-required',
                lossState: 'loss-state-required'
            }
        };
    },
    computed: {
        DamageCauseOptions() {
            const damageCauseAnswers = this.getCmsContent('DamageCauseQuestion', 'Answers');
            const damageCauseAnswersObj = {};
            if (damageCauseAnswers) {
                // eslint-disable-next-line no-restricted-syntax
                for (const answer of Object.values(damageCauseAnswers)) {
                    if (answer?.Name) {
                        damageCauseAnswersObj[answer.Name] = answer.Name;
                    }
                }
            }
            return damageCauseAnswersObj;
        },
        DamageGlassOnlyOptions() {
            return this.getCmsContent('GlassOnlyQuestion', 'Answers');
        },
        DamageGlassOnlyQuestion() {
            return this.getCmsContent('GlassOnlyQuestion', 'QuestionText');
        },
        displayDamageCityQuestion() {
            return !!this.getCmsContent('DamageCityQuestion', 'QuestionText');
        },
        displayDamageStateQuestion() {
            return !!this.getCmsContent('DamageStateQuestion', 'QuestionText');
        },
        displayGlassOnlyQuestion() {
            return !!this.getCmsContent('GlassOnlyQuestion', 'QuestionText');
        },
        getStates() {
            return states;
        },
        isPolicyHolderEnabled() {
            return !!this.mainStore.issConfig.disabledFields.policyNumber;
        },
        isCoverageEnabled() {
            return this.mainStore.issConfig.isCoverageEnabled;
        }
    },
    methods: {
        async forwardButtonAction() {
            this.mainStore.updatePolicyData(this.welcomePageModel);

            // call coverage policy lookup if isCoverageEnabled flag enabled
            if (this.isCoverageEnabled) {
                const policyLookupResponse = useMainStore().getCoveragePolicyInfo({
                    accountNumber: this.mainStore.order.accountNumber.toString(),
                    policyNumber: this.mainStore.order.policy.policyNumber,
                    dateOfLoss: this.mainStore.order.policy.dateOfLoss,
                    zipCode: this.mainStore.order.policy.policyZipCode
                });

                // Settle promises and get results
                const promisePolicyLookupResultMap = [
                    {
                        resultKey: 'policyLookupResponse',
                        promise: policyLookupResponse
                    }
                ];

                const policyLookupResultMap = await settleAllPromises(promisePolicyLookupResultMap);
                const policyInfo = policyLookupResultMap.policyLookupResponse;

                // if policy lookup fails, navigate directly to policy-holder-details page
                if (!policyInfo) {
                    this.navigateForward();
                }

                const policy = policyInfo.policies?.[0];
                if (policy) {
                    // populate policy holder details from policy lookup
                    this.mainStore.order.customer.address.streetAddress =
                        policy.insureds?.[0]?.address;
                    this.mainStore.order.customer.address.city = policy.insureds?.[0]?.city;
                    this.mainStore.order.customer.address.state = policy.insureds?.[0]?.state;
                    this.mainStore.order.customer.address.zipCode = policy.insureds?.[0]?.zipCode;
                    this.mainStore.order.customer.firstName = policy.insureds?.[0]?.firstName;
                    this.mainStore.order.customer.lastName = policy.insureds?.[0]?.lastName;

                    // populate vehicles
                    this.vehiclesFound = policy.vehicles;
                }
                return this.navigateForward(policy);
            }
            return this.navigateForward();
        },

        navigateForward(policy) {
            if (policy) {
                if (this.vehiclesFound) {
                    // if policy lookup is successful and vehicles are found, navigate to policy-vehicles page
                    this.$router.navigate(
                        this.navigationScenarios.CLICKED_FORWARD_POLICY_VERIFIED_WITH_VEHICLES,
                        this.$route,
                        {},
                        {},
                        this.vehiclesFound
                    );
                } else {
                    // if policy lookup is successful, but no vehicles are associated with the policy
                    // navigate to vehicle-selection page (manual entry)
                    this.$router.navigate(
                        this.navigationScenarios.CLICKED_FORWARD_POLICY_VERIFIED_NO_VEHICLES,
                        this.$route
                    );
                }
            } else {
                // if policy lookup is unsuccessful, navigate to policy-holder-details page
                this.$router.navigate(
                    this.navigationScenarios.CLICKED_FORWARD_POLICY_UNVERIFIED,
                    this.$route
                );
            }
        },

        getWelcomePageModelFromStore() {
            return {
                policyNumber: this.mainStore.order.policy.policyNumber,
                policyZipCode: this.mainStore.order.policy.policyZipCode,
                dateOfLoss: this.mainStore.order.policy.dateOfLoss,
                damageCause: this.mainStore.order.policy.damageCause,
                damageState: this.mainStore.order.policy.damageState,
                damageCity: this.mainStore.order.policy.damageCity,
                isDamageGlassOnly: this.mainStore.order.policy.isDamageGlassOnly,
                phoneNumber: this.mainStore.order.customer.phoneNumber,
                email: this.mainStore.order.customer.emailAddress,
                isPolicyNumberDisabled: this.mainStore.order.policy.isPolicyNumberDisabled
            };
        }
    }
};
</script>

<style lang="scss">
.page-container-grouped-styles.welcome {
    height: auto;
}
@-moz-document url-prefix() {
    // Temporary solution that prevents the Continue button from being hidden in Firefox
    #welcomeFooter {
        position: static !important;
    }
    // Fixes Firefox styling defect for placeholder text in dropdown fields
    #welcomeDropdown {
        .form-select {
            padding: 0.75rem 1rem;
        }
    }
}
</style>
