<template>
<Form @submit="onSubmit" @invalid-submit="onInvalidSubmit" ref="theForm"  v-slot="{ meta }" >

    <div class="page-container-grouped-styles welcome small-question-label-text">
        <siteHeader cmsWidgetName="SiteHeaderWidget"/>
        <div class="fade-on-route-transition  overflow-scroll container">

            <siteSubHeader cmsWidgetName="SiteSubHeaderWidget"/>
            <div class="row mt-4 px-3">
                <div class="col">
                    <textboxQuestion
                        inputId="policyNumberField"
                        cmsWidgetName="PolicyNumberQuestion"
                        v-model="welcomePageModel.policyNumber"
                        isRequired
                        ref="policyNumber"
                        disableAutoFill
                        validationRules="policy-number-required" />
                </div>
            </div>
            <div class="row mt-4 px-3">
                <div class="col">
                    <textboxQuestion
                        type="date"
                        cmsWidgetName="DateOfLossQuestion"
                        v-model="welcomePageModel.dateOfLoss"
                        inputId="dateOfLossField"
                        isRequired
                        ref="dateOfLoss"
                        disableAutoFill
                        :max="new Date().toJSON().slice(0,10)"
                        :min="'1972-12-01'"
                        validationRules="loss-date-required"                        
                />
                </div>
            </div>
            <div class="row px-5">
                <div class="col px-0">
                    <textBlock cmsWidgetName="DamageDateEstimateWidget" typeStyle="small" class="mt-2" />
                </div>
            </div>
            <div class="row mt-4 px-3">
                <div class="col">
                    <dropdownQuestion
                        cmsWidgetName="DamageCauseQuestion"
                        v-model="welcomePageModel.damageCause"
                        ref="damageCause"
                        inputId="damageCauseQuestionField"
                        :options="DamageCauseOptions"
                        disableAutoFill
                        validationRules="damage-option-required"
                        placeHolderText="Select an option"
                        id="welcomeDropdown"
                    />
                </div>
            </div>  
            <div class="row mt-4 px-3">
                <div class="col">
                    <textboxQuestion
                        inputId="phoneNumberField"
                        cmsWidgetName="PhoneNumberQuestion"
                        v-model="welcomePageModel.phoneNumber"
                        validationRules="phone-number-required|phone-number-format"
                        isRequired
                        ref="phoneNumber"
                        mask="###-###-####"
                        disableAutoFill />
                </div>
            </div>
            <div class="row mt-4 px-3">
                <div class="col">
                    <textboxQuestion
                        inputId="emailField"
                        cmsWidgetName="EmailAddressQuestion"
                        v-model="welcomePageModel.email"
                        ref="email"
                        validationRules="email-address-required|email-address-format"
                        isRequired
                        disableAutoFill />
                </div>
            </div>
            <div class="row mt-4 px-3">
                <div class="col">
                    <textboxQuestion
                        inputId="damageCityField"
                        cmsWidgetName="DamageCityQuestion"
                        v-model="welcomePageModel.damageCity"
                        isRequired
                        ref="damageCity"
                        disableAutoFill
                        v-if="this.displayDamageCityQuestion"
                        validationRules="loss-city-required" />
                </div>
            </div>
            <div class="row mt-4 px-3">
                <div class="col">
                    <dropdownQuestion
                        cmsWidgetName="DamageStateQuestion"
                        v-model="welcomePageModel.damageState"
                        ref="state"
                        inputId="8fdf9dc2e13e430eb57529499dceb3eb"
                        :options="stateOptions"
                        validationRules="loss-state-required"
                        isRequired
                        disableAutoFill
                        v-if="this.displayDamageStateQuestion"
                        placeHolderText="Select an option"
                        id="welcomeDropdown"
                    />
                </div>
            </div>
            <div class="row mt-4">
                    <buttonQuestion
                        class="px-0"
                        cmsWidgetName="GlassOnlyQuestion"
                        v-model="welcomePageModel.isDamageGlassOnly"
                        inputId = "isDamageGlassOnly"
                        :answers="DamageGlassOnlyOptions"
                        :questionText="DamageGlassOnlyQuestion"
                        buttonTypeString="listButtonHorizontal"
                        validationRules="damage-option-required"
                        isRequired
                        ref="glassOnlyDamage"
                        v-if="this.displayGlassOnlyQuestion"
                        disableAutoFill/>
            </div>
            <div class="row mt-4 position-sticky top-100" id="welcomeFooter">
                <div class="col">
                    <site-footer
                        cmsWidgetName="SiteFooterWidget"
                        :isForwardActionDisabled="!meta.valid"
                        @back-clicked="backButtonAction"
                        @ForwardClicked="forwardButtonAction" />
                </div>
            </div>
        </div>
    </div>
</Form>
</template>

    <script>
    // Components
    import siteHeader from '@/iss-components/site-header/site-header';
    import siteSubHeader from '@/iss-components/site-sub-header/site-sub-header';
    import siteFooter from "@/iss-components/site-footer/site-footer";
    import textboxQuestion from "@/digital-components/textbox-question/textbox-question";
    import buttonQuestion from "@/digital-components/button-question/button-question";
    import dropdownQuestion from "@/digital-components/dropdown-question/dropdown-question";
    import textBlock from "@/digital-components/text-block/text-block";

    // 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';

    //define validation rules
    defineRule("loss-date-required", required(errorMessages.LOSS_DATE_REQUIRED));
    defineRule("loss-cause-required", required(errorMessages.LOSS_CAUSE_REQUIRED));
    defineRule("policy-number-required", required(errorMessages.POLICY_NUMBER_REQUIRED));
    defineRule("loss-date-required", required(errorMessages.LOSS_DATE_REQUIRED));
    defineRule("loss-state-required", required(errorMessages.LOSS_STATE_REQUIRED));
    defineRule("loss-city-required", required(errorMessages.LOSS_CITY_REQUIRED));
    defineRule("phone-number-required", required(errorMessages.PHONE_NUMBER_FORMAT));
    defineRule("email-address-required", required(errorMessages.EMAIL_ADDRESS_REQUIRED));
    defineRule("damage-option-required", required(errorMessages.DAMAGE_OPTION_REQUIRED));

    defineRule("email-address-format",
        regex(
            /^([a-zA-Z0-9_\-.+]+)@([a-zA-Z0-9_\-.]+)\.([a-zA-Z]{2,})$/,
            errorMessages.EMAIL_ADDRESS_FORMAT
        )
    );

    defineRule("phone-number-format",
        regex(
            /^(\([0-9]{3}\)|[0-9]{3}) *[-.]? *[0-9]{3} *[-.]? *[0-9]{4}$/,
            errorMessages.PHONE_NUMBER_FORMAT
        )
    );

    export default {
        name: "welcome-page",
        mixins: [BaseFormMixin],
        data() {
            return {
                welcomePageModel: this.getWelcomePageModelFromStore()                
            };            
        },
        setup() {
            const mainStore = useMainStore();

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

            return { mainStore };
        },
        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.
            let resultMap = await settleAllPromises(promiseResultMap);
           
            next((vm) => {
                vm.setCmsContent(resultMap.cmsContent);                
            });
        },
        methods:
        {
            async forwardButtonAction() {
                this.mainStore.updatePolicyData(this.welcomePageModel);
                return this.navigateForward();
            },

            navigateForward() {
                this.$router.navigate(
                    this.navigationScenarios.CLICKED_FORWARD_WELCOME_PAGE,
                    this.$route
                );
            },
            getWelcomePageModelFromStore() {
                return {
                    policyNumber : this.mainStore.order.policy.policyNumber,
                    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,
                }
            },
        },
        computed:{
            DamageCauseOptions() {
                const damageCauseAnswers =  this.getCmsContent("DamageCauseQuestion", "Answers");
                const damageCauseAnswersObj ={};
                if(damageCauseAnswers)
                {
                   for (let 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");
            },
            stateOptions: {
                get: function () {
                    return {
                        AL: "Alabama",
                        AK: "Alaska",
                        AZ: "Arizona",
                        AR: "Arkansas",
                        CA: "California",
                        CO: "Colorado",
                        CT: "Connecticut",
                        DE: "Delaware",
                        DC: "District Of Columbia",
                        FL: "Florida",
                        GA: "Georgia",
                        HI: "Hawaii",
                        ID: "Idaho",
                        IL: "Illinois",
                        IN: "Indiana",
                        IA: "Iowa",
                        KS: "Kansas",
                        KY: "Kentucky",
                        LA: "Louisiana",
                        ME: "Maine",
                        MD: "Maryland",
                        MA: "Massachusetts",
                        MI: "Michigan",
                        MN: "Minnesota",
                        MS: "Mississippi",
                        MO: "Missouri",
                        MT: "Montana",
                        NE: "Nebraska",
                        NV: "Nevada",
                        NH: "New Hampshire",
                        NJ: "New Jersey",
                        NM: "New Mexico",
                        NY: "New York",
                        NC: "North Carolina",
                        ND: "North Dakota",
                        OH: "Ohio",
                        OK: "Oklahoma",
                        OR: "Oregon",
                        PA: "Pennsylvania",
                        RI: "Rhode Island",
                        SC: "South Carolina",
                        SD: "South Dakota",
                        TN: "Tennessee",
                        TX: "Texas",
                        UT: "Utah",
                        VT: "Vermont",
                        VA: "Virginia",
                        WA: "Washington",
                        WV: "West Virginia",
                        WI: "Wisconsin",
                        WY: "Wyoming",
                    };
                },
            },
            displayDamageCityQuestion(){
                return !!this.getCmsContent("DamageCityQuestion","QuestionText");
            },
            displayDamageStateQuestion(){                
                return !!this.getCmsContent("DamageStateQuestion","QuestionText");
            },
            displayGlassOnlyQuestion(){
                return !!this.getCmsContent("GlassOnlyQuestion","QuestionText");
            }
        },
        components: {
            siteHeader,
            siteSubHeader,
            buttonQuestion,
            textboxQuestion,
            dropdownQuestion,
            siteFooter,
            textBlock,
            Form,
        },
    }
</script>

<style lang="scss">

.overflow-scroll {    
    height: calc(100% - 165px);   
    overflow-X: hidden !important;   
}
.my-2
{
    margin-bottom: 0rem !important;
}
@-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>
