<template>
    <Form
        ref="duplicate-check-form"
        v-slot="{ meta }"
        @submit="onSubmit"
        @invalidSubmit="onInvalidSubmit">
        <div class="fade-on-route-transition">
            <div class="justify-content-center">
                <siteHeader
                    ref="siteHeader"
                    :cmsWidgetName="widget.siteHeader" />
            </div>
            <div class="iss-heritage-container-width">
                <div class="duplicate-check-container iss-heritage-content-container-width">
                    <siteSubHeader
                        id="sub-header"
                        ref="siteSubHeader"
                        class="mt-4 duplicate-check-subheader"
                        :cmsWidgetName="widget.siteSubHeader" />
                    <buttonQuestion
                        ref="buttonQuestion"
                        v-model="selectedAnswer"
                        class="duplicate-check-question"
                        :cmsWidgetName="widget.existingOrNewQuestion"
                        :questionText="questionText"
                        :answers="duplicateOrders"
                        groupName="existingOrNewQuestionOption"
                        buttonTypeString="listButton"
                        isRequired
                        :validationRules="rules.selectionRequired" />
                    <buttonMain
                        :variant="buttonVariants.primary"
                        buttonText="Start a new claim"
                        class="mt-5 w-100"
                        @clickEvent="startNewClaim" />
                    <siteFooter
                        ref="siteFooter"
                        class="my-5"
                        :cmsWidgetName="widget.siteFooter"
                        :isForwardActionDisabled="!meta.valid"
                        @forwardClicked="forwardButtonAction"
                        @backClicked="navigateBack" />
                </div>
            </div>
        </div>
    </Form>
</template>

<script>
// Components
import { Form } from 'vee-validate';
import siteHeader from '@/iss-components/site-header/site-header.vue';
import siteFooter from '@/iss-components/site-footer/site-footer.vue';
import siteSubHeader from '@/iss-components/site-sub-header/site-sub-header.vue';
import buttonQuestion from '@/digital-components/button-question/button-question.vue';
import buttonMain from '@/ux-components/button-main/button-main.vue';
import { buttonVariants } from '@/constants/component-variants';

// Supporting files
import { fetchCmsContentForPage } from '@/helpers/cms-content-helper.js';
import BaseFormMixin from '@/mixins/base-form-mixin.js';
import { useMainStore } from '@/store/index.js';
import globalRules from '@/constants/global-rules.js';
import { formatDate, toTitleCase } from '@/helpers/text-helper.js';
import { saveSession } from '@/helpers/order-helper';
import showIssLoadingModal from '@/helpers/loading-modal-helper';

const dupeCheckDateFormatter = new Intl.DateTimeFormat('en-US', { timeZone: 'UTC', month: '2-digit', day: '2-digit', year: 'numeric' });

export default {
    name: 'duplicate-check',
    components: {
        siteHeader,
        siteSubHeader,
        buttonQuestion,
        siteFooter,
        Form,
        buttonMain
    },
    mixins: [BaseFormMixin],
    async beforeRouteEnter(to, from, next) {
        const cmsContent = await fetchCmsContentForPage(to.query.issPage);

        next((vm) => {
            vm.setCmsContent(cmsContent);
        });
    },
    setup() {
        const mainStore = useMainStore();
        return { mainStore };
    },
    data() {
        return {
            selectedAnswer: null,
            widget: {
                siteHeader: 'SiteHeaderWidget',
                siteSubHeader: 'SiteSubHeaderWidget',
                existingOrNewQuestion: 'ExistingOrNewQuestion',
                siteFooter: 'SiteFooterWidget'
            },
            rules: {
                selectionRequired: globalRules.OPTION_REQUIRED
            },
            buttonVariants
        };
    },
    computed: {
        questionText() {
            return this.getCmsContent(this.widget.existingOrNewQuestion, 'QuestionText');
        },
        duplicateOrders() {
            const duplicateOrderText = 'Finish existing claim';
            const orders = useMainStore().applicationUser.duplicateOrders;
            return (
                orders?.map((o) => {
                    const vehicle = !!o.vehicleYear && !!o.vehicleMake && !!o.vehicleModel
                        ? `${o.vehicleYear} ${o.vehicleMake} ${o.vehicleModel}`
                        : null;
                    const dateOfLoss = formatDate(new Date(useMainStore().order.policy.dateOfLoss), dupeCheckDateFormatter);
                    const subtext = vehicle
                        ? `${vehicle}, ${dateOfLoss}`
                        : (vehicle ?? '').concat(dateOfLoss);

                    return {
                        Text: duplicateOrderText,
                        Name: o.referralNumber,
                        SubText: toTitleCase(subtext),
                        value: o.correlationId
                    };
                }) ?? []
            );
        }
    },
    methods: {
        /**
         * @summary Steps to perform when forward button clicked.
         */
        async forwardButtonAction() {
            showIssLoadingModal(true);

            let callSaveSession = false;

            // If user clicked forward without selecting an option or user click on "start a new claim" button.
            if (this.selectedAnswer == null || this.selectedAnswer === 'NewClaim') {
                // User did not pick a duplicate, so call SaveSession to create referral.
                callSaveSession = true;
            }
            else
            {
                const selectedReferral =
                    this.mainStore.applicationUser.duplicateOrders.find((o) => o.correlationId === this.selectedAnswer);

                if (selectedReferral) {
                    // LoadSession will bailout on error.
                    await this.mainStore.loadSessionFromDuplicate(selectedReferral);
                }
                else {
                    // If duplicate not found in list (unable to load), then call SaveSession to create referral.
                    callSaveSession = true;
                }
            }

            try
            {
                // Call SaveSession to create referral.
                if ( callSaveSession ) {
                    // SaveSession will bailout on error.
                    await saveSession({ shouldAwaitSaveSessionQueue: true, bailoutOnError: true });
                }
                
                // Call getCoveragePolicyInfo to get the policy info.
                await this.mainStore.getCoveragePolicyInfo();
            }
            catch (error) {
                // No error handling here needed.
                // GetCoveragePolicyInfo handles exception / error internally. We do not care if it fails, user continues in unverified path.
            }
                
            this.pushEventToGA("policy_search", "policy_found", this.mainStore.isPolicyLookupSuccessful ? "Yes" : "No", true);

            if ( this.mainStore.isPolicyLookupSuccessful) {
                this.pushEventToGA("zip_validation", "success", "N/A", true);
            }
            else {
                if ( this.mainStore.order.policy.policyLookupErrorCode === 2) {
                    this.pushEventToGA("zip_validation", "fail", "N/A", true);
                }
            }

            this.navigateForward();
        },
        navigateForward() {
            this.mainStore.updateDuplicateCheckVisited(true);

            if (!this.mainStore.isPolicyLookupSuccessful) {
                this.$router.navigate(
                    this.navigationScenarios.CLICKED_FORWARD_POLICY_UNVERIFIED,
                    this.$route
                );
                return;
            }

            const policyVehicles = useMainStore().order.policy.vehicles ?? [];

            if (!this.mainStore.order.loadedFromDupeCheck) {
                if (policyVehicles.length !== 0) {
                    this.$router.navigate(
                        this.navigationScenarios.CLICKED_FORWARD_POLICY_VERIFIED_WITH_VEHICLES,
                        this.$route
                    );
                } else {
                    this.$router.navigate(
                        this.navigationScenarios.CLICKED_FORWARD_POLICY_VERIFIED_NO_VEHICLES,
                        this.$route
                    );
                }
                return;
            }

            if (this.mainStore.order.vehicle.vin) {
                this.$router.navigate(
                    this.navigationScenarios.CLICKED_FORWARD_LOADED_DUPLICATE_WITH_POLICY_VEHICLE,
                    this.$route
                );
            } else if (policyVehicles.length !== 0) {
                this.$router.navigate(
                    this.navigationScenarios.CLICKED_FORWARD_LOADED_DUPLICATE_WITH_NON_POLICY_VEHICLE,
                    this.$route
                );
            } else {
                this.$router.navigate(
                    this.navigationScenarios.CLICKED_FORWARD_LOADED_DUPLICATE_WITH_NO_POLICY_VEHICLES,
                    this.$route
                );
            }
        },
        async startNewClaim() {
            this.selectedAnswer = 'NewClaim';
            await this.forwardButtonAction();
        }
    }
};
</script>

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

.duplicate-check-subheader {
    .subheader-secondary {
        margin-top: map-get($spacers, 2);
    }
}

.duplicate-check-question {
    .question-text {
        justify-content: left;
        display: inline-flex !important;
        margin-top: map-get($spacers, 4);
        margin-bottom: 0.625rem !important;
        span {
            font-weight: 600;
        }
    }
    .form-test-error {
        margin-top: 0 !important;
        span {
            font-weight: 500;
        }
    }
    .question-text.d-flex {
        margin-top: 0;
    }
}

.list-button-content {
    span.small {
        font-weight: 400;
    }
}

.form-group {
    margin-bottom: 1.25rem !important;
}
</style>
