<template>
    <Form
        ref="theForm"
        v-slot="{ meta }"
        @submit="onSubmit"
        @invalidSubmit="onInvalidSubmit">
        <div class="container-fluid fade-on-route-transition">
            <div class="row justify-content-center">
                <div class="col-md-6 px-0 px-md-2">
                    <siteHeader
                        ref="siteHeader"
                        cmsWidgetName="SiteHeaderWidget" />
                </div>
            </div>
            <div class="row justify-content-center">
                <div class="col-md-6 col-xl-4">
                    <vehicleBanner
                        ref="vehicleBanner"
                        class="mb-4"
                        cmsWidgetName="VehicleBannerWidget"
                        :displayGenericVehicleImage="false" />
                    <div class="text-center text-color--black pb-2 fs-5">
                        <img :src="tpaConfirmationImage" />
                        <span
                            class="ms-2"
                            v-html="tpaConfirmationHeaderText"></span>
                    </div>
                    <div class="text-center text-color--black mb-3 fw-bold">
                        <span v-html="tpaConfirmationSubheaderText"></span>
                    </div>
                    <textBlock
                        ref="tpaConfirmationBodyOne"
                        class="tpa-body-one mt-0"
                        :customText="tpaConfirmationBodyOne" />
                    <textBlock
                        ref="tpaConfirmationBodyTwo"
                        :customText="tpaConfirmationBodyTwo"
                        class="small mt-0 mb-4" />
                    <textBlock
                        id="contactCarrierText"
                        ref="contactCarrierText"
                        :customText="contactCarrierText"
                        class="contact-carrier-text small"
                        @click="setBailoutInfo()" />
                    <div ref="confirmationOrderDetailsSection">
                        <textBlock
                            ref="tpaConfirmationOrderDetailsTitle"
                            :customText="orderDetailsTitle"
                            class="text-color--black fw-bold lh-base mt-5 mb-4"
                            :marginTopSizeOverride="4" />
                        <textBlock
                            id="tpaConfirmationOrderDetailsBody"
                            ref="tpaConfirmationOrderDetailsBody"
                            :customText="orderDetailsBody"
                            :marginTopSizeOverride="4"
                            class="mb-4 small" />
                        <deductibleBox
                            ref="deductibleBox"
                            :value="deductibleBoxValue" />
                    </div>
                    <siteFooter
                        v-if="carrierUrl"
                        ref="siteFooter"
                        cmsWidgetName="SiteFooterWidget"
                        :isStackedVertically="true"
                        :isForwardActionDisabled="!meta.valid"
                        @ForwardClicked="forwardButtonAction"
                        @backClicked="navigateBack" />
                </div>
            </div>
        </div>
    </Form>
</template>
<script>
// Components
import siteHeader from '@/iss-components/site-header/site-header.vue';
import vehicleBanner from '@/iss-components/vehicle-banner/vehicle-banner.vue';
import siteFooter from '@/iss-components/site-footer/site-footer.vue';
import textBlock from '@/digital-components/text-block/text-block.vue';
import deductibleBox from '@/layouts/tpa-submit/deductible-box/deductible-box.vue';

// Supporting files
import {
    fetchCmsContentForPage,
    processIfStatements,
} from '@/helpers/cms-content-helper';
import settleAllPromises from '@/helpers/layout-helper';
import { Form } from 'vee-validate';
import BaseFormMixin from '@/mixins/base-form-mixin.js';
import { useMainStore } from '@/store';
import {
    toTitleCase,
    toDisplayPhoneNumber,
    formatAmountInDollars,
} from '@/helpers/text-helper.js';
import bailoutMessage from '@/constants/bailoutMessage';

const VERIFYING_COVERAGE = 'Verifying coverage';

export default {
    name: 'tpa-confirmation',
    components: {
        siteHeader,
        siteFooter,
        vehicleBanner,
        textBlock,
        deductibleBox,
        // 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);
        const accountInfoPromise = useMainStore().getCarrierAccountInfo();
        // Settle promises and get results
        const promiseResultMap = [
            {
                resultKey: 'cmsContent',
                promise: cmsContentPromise,
            },
            {
                resultKey: 'accountInfo',
                promise: accountInfoPromise,
            },
        ];
        // use resultMap to populate layout content.
        const resultMap = await settleAllPromises(promiseResultMap);
        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);
        });
    },
    setup() {
        const mainStore = useMainStore();
        return { mainStore };
    },
    computed: {
        tpaConfirmationHeaderText() {
            return this.getCmsContent('TPAConfirmationContent', 'HeaderText');
        },
        tpaConfirmationImage() {
            return this.getCmsContent('TPAConfirmationContent', 'Image');
        },
        tpaConfirmationSubheaderText() {
            return this.getCmsContent(
                'TPAConfirmationContent',
                'SubheaderText'
            )?.replaceAll('{custom:glassShop}', this.preferredShopName);
        },
        tpaConfirmationBodyOne() {
            return this.getCmsContent('TPAConfirmationContent', 'BodyText')
                ?.replaceAll(
                    '{custom:phoneNumber}',
                    this.preferredShopPhoneNumber
                )
                ?.replaceAll('{custom:glassShop}', this.preferredShopName);
        },
        tpaConfirmationBodyTwo() {
            return this.getCmsContent('TPAConfirmationContent', 'BodyText2');
        },
        contactCarrierText() {
            const contactCarrierText = this.getCmsContent(
                'ContactCarrierContent',
                'Text'
            )?.replaceAll(
                '{custom:carrierPhoneNumber}',
                this.carrierPhoneNumber
            );
            return this.processIfStatements(
                contactCarrierText,
                'custom',
                this.getCustomValueFromString
            );
        },
        orderDetailsTitle() {
            return this.getCmsContent('OrderDetailsContent', 'HeaderText');
        },
        orderDetailsBody() {
            const orderDetailsBodyText = this.getCmsContent(
                'OrderDetailsContent',
                'BodyText'
            );
            return this.processIfStatements(
                orderDetailsBodyText,
                'custom',
                this.getCustomValueFromString
            );
        },
        deductibleBoxValue() {
            return this.isVerified
                ? this.formatAmountInDollars(this.currentDeductible)
                : VERIFYING_COVERAGE;
        },
        currentDeductible() {
            return useMainStore().order.currentDeductible;
        },
        preferredShopName() {
            return toTitleCase(
                useMainStore().order.serviceLocation.provider.companyName
            );
        },
        preferredShopPhoneNumber() {
            return this.toDisplayPhoneNumber(
                useMainStore().order.serviceLocation.provider.phoneNumber
            );
        },
        isVerified() {
            return useMainStore().order.payment.insuranceCoverage.isVerified;
        },
        carrierName() {
            return this.mainStore.issConfig.clientName;
        },
        carrierUrl() {
            return this.mainStore.issConfig.successReturnURL;
        },
        carrierPhoneNumber() {
            return this.toDisplayPhoneNumber(
                useMainStore().order.carrierPhoneNumber
            );
        },
    },
    mounted() {
        if (this.carrierUrl) {
            this.$refs.siteFooter.updateButtonText(
                `Go back to ${this.carrierName}`
            );
        }
    },
    methods: {
        async forwardButtonAction() {
            this.$router.navigateToExternalUrl(this.carrierUrl);
        },
        getCustomValueFromString(str) {
            switch (str) {
                case 'deductibleAboveZero':
                    return this.isVerified && this.currentDeductible !== 0;
                case 'zeroDeductible':
                    return this.isVerified && this.currentDeductible === 0;
                case 'verifyingCoverage':
                    return !this.isVerified;
                case 'coverageVerified':
                    return this.isVerified;
                default:
                    return null;
            }
        },
        setBailoutInfo() {
            this.mainStore.setBailout(bailoutMessage.RequestCallback);
        },
        toDisplayPhoneNumber,
        formatAmountInDollars,
        processIfStatements,
    },
};
</script>
<style lang="scss" scoped>
.text-color--black {
    color: $black;
}

.tpa-body-one {
    :deep(p) {
        line-height: map-get($spacers, 5);
        font-size: $h6-font-size;

        strong {
            color: $black;
        }
    }
}

.contact-carrier-text {
    :deep(a) {
        font-weight: $font-weight-bold;
    }
}
</style>
