<template>
    <Form
        ref="theForm"
        v-slot="{ meta }"
        @submit="onSubmit"
        @invalidSubmit="onInvalidSubmit">
        <div class="fade-on-route-transition">
            <div class="justify-content-center">
                <siteHeader
                    ref="siteHeader"
                    cmsWidgetName="SiteHeaderWidget" />
            </div>
            <div class="iss-heritage-container-width">
                <div class="tpa-confirmation-container iss-heritage-content-container-width">
                    <div class="d-flex justify-content-center align-items-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" />
                    <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"
                            class="px-3"
                            :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 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';

const VERIFYING_COVERAGE = 'Verifying coverage';

export default {
    name: 'tpa-confirmation',
    components: {
        siteHeader,
        siteFooter,
        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);
        // 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();
        const submittedOrder = mainStore.getSubmittedOrder();
        return { mainStore, submittedOrder };
    },
    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');
        },
        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 this.submittedOrder.currentDeductible;
        },
        preferredShopName() {
            return toTitleCase(this.submittedOrder.serviceLocation.provider.companyName);
        },
        preferredShopPhoneNumber() {
            return this.toDisplayPhoneNumber(this.submittedOrder.serviceLocation.provider.phoneNumber);
        },
        isVerified() {
            return this.submittedOrder.isVerified;
        },
        carrierName() {
            return this.mainStore.issConfig.clientName;
        },
        carrierUrl() {
            return this.mainStore.issConfig.successReturnURL;
        },
        carrierPhoneNumber() {
            return this.toDisplayPhoneNumber(this.submittedOrder.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;
            }
        },
        toDisplayPhoneNumber,
        formatAmountInDollars,
        processIfStatements
    }
};
</script>
<style lang="scss" scoped>
.iss-heritage-container-width {
    .tpa-confirmation-container {
        position: relative;
        min-height: 1px;
        padding-left: .9375rem;
        padding-right: .9375rem;
    }
}

.text-color--black {
    color: $black;
}

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

        strong {
            color: $black;
        }
    }
}
</style>
