<template>
    <Form
        ref="duplicate-check-form"
        v-slot="{ meta }"
        @submit="onSubmit"
        @invalidSubmit="onInvalidSubmit">
        <div class="page-container-grouped-styles">
            <div class="fade-on-route-transition">
                <siteHeader
                    ref="siteHeader"
                    :cmsWidgetName="widget.siteHeader" />
                <div class="container-fluid px-6">
                    <siteSubHeader
                        id="sub-header"
                        ref="siteSubHeader"
                        class="mt-5 duplicate-check-subheader"
                        :cmsWidgetName="widget.siteSubHeader" />
                    <buttonQuestion
                        ref="buttonQuestion"
                        v-model="selectedAnswer"
                        class="duplicate-check-question"
                        :cmsWidgetName="widget.existingOrNewQuestion"
                        :questionText="questionText"
                        :answers="answers"
                        groupName="existingOrNewQuestionOption"
                        buttonTypeString="listButton"
                        isRequired
                        :validationRules="rules.selectionRequired">
                    </buttonQuestion>
                    <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';

// 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 { toTitleCase } from '@/helpers/text-helper.js';

export default {
    name: 'duplicate-check',
    components: {
        siteHeader,
        siteSubHeader,
        buttonQuestion,
        siteFooter,
        // eslint-disable-next-line vue/no-reserved-component-names
        Form
    },
    mixins: [BaseFormMixin],
    async beforeRouteEnter(to, from, next) {
        const cmsContent = await fetchCmsContentForPage(to.query.issPage);

        next((vm) => {
            vm.setCmsContent(cmsContent);
        });
    },
    data() {
        return {
            selectedAnswer: '',
            widget: {
                siteHeader: 'SiteHeaderWidget',
                siteSubHeader: 'SiteSubHeaderWidget',
                existingOrNewQuestion: 'ExistingOrNewQuestion',
                siteFooter: 'SiteFooterWidget'
            },
            rules: {
                selectionRequired: globalRules.OPTION_REQUIRED
            }
        };
    },
    computed: {
        questionText() {
            return this.getCmsContent(this.widget.existingOrNewQuestion, 'QuestionText');
        },
        answersFromCms() {
            return this.getCmsContent(this.widget.existingOrNewQuestion, 'Answers') ?? [];
        },
        getNewOrderSelectionName() {
            return this.answersFromCms?.[0]?.Name ?? '';
        },
        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 = o.responseDate == null ? '' : new Date(o.responseDate).toLocaleDateString();
                const subtext = vehicle && o.responseDate
                    ? `${vehicle}, ${dateOfLoss}`
                    : (vehicle ?? '').concat(dateOfLoss);

                return {
                    Text: duplicateOrderText,
                    Name: o.referralNumber,
                    SubText: toTitleCase(subtext)
                };
            }) ?? [];
        },
        answers() {
            return [...this.duplicateOrders, ...this.answersFromCms];
        }
    },
    methods: {
        /**
         * @summary Steps to perform when forward button clicked.
         */
        async forwardButtonAction() {
            if (this.selectedAnswer !== this.getNewOrderSelectionName) {
                await useMainStore().loadSession()
                    .then(() => {}, () => {})
                    .finally(() => { this.navigateForward(); });
            } else {
                this.navigateForward();
            }
        },
        navigateForward() {
            if (useMainStore().order.policy.policyLookupSuccessful) {
                const policyVehicles = useMainStore().order.policy.vehicles ?? [];
                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
                    );
                }
            } else {
                this.$router.navigate(
                    this.navigationScenarios.CLICKED_FORWARD_POLICY_UNVERIFIED,
                    this.$route
                );
            }
        }
    }
};
</script>

<style lang="scss">
.duplicate-check-subheader {
    .subheader-secondary {
        margin-top: map-get($spacers, 2);
    }
    p {
        span {
            font-size: $h6-font-size;
        }
    }
}
.duplicate-check-question {
    .question-text {
        justify-content: left;
        display: inline-flex !important;
        margin-top: map-get($spacers, 4);
        margin-bottom: map-get($spacers, 2);
    }
    .form-test-error{
        margin-top: 0 !important;
    }
}

</style>
