<!-- eslint-disable vue/no-v-html -->
<template>
    <Form
        ref="theForm"
        v-slot="{ meta }"
        @submit="onSubmit"
        @invalidSubmit="onInvalidSubmit">
        <div class="fade-on-route-transition coverage-statement">
            <div class="justify-content-center">
                <siteHeader
                    ref="siteHeader"
                    cmsWidgetName="SiteHeaderWidget" />
            </div>
            <div class="iss-heritage-container-width">
                <div class="coverage-statement-container iss-heritage-content-container-width">
                    <h5
                        ref="siteSubHeader"
                        class="sub-header text-black"
                        v-html="coverageStatementSubHeader"></h5>
                    <div
                        ref="explanatoryText"
                        class="body-text"
                        v-html="explanatoryText"></div>
                    <div
                        ref="explanatoryText2"
                        class="body-text mt-3"
                        v-html="explanatoryText2"></div>
                    <div
                        ref="secondaryText"
                        class="mt-4 mb-1 fw-bold text-black"
                        v-html="secondaryText"></div>
                    <div
                        v-if="isITACQuoteVisible"
                        class="itac-price-container">
                        <div class="itac-deductible-value-container">
                            <div class="itac-deductible-value-text">
                                Your deductible:
                            </div>
                            <div class="itac-deductible-value">
                                {{ formatAmountInDollars(deductibleValue) }}
                            </div>
                        </div>
                        <div class="separator"></div>
                        <div class="itac-cost-container">
                            <div class="itac-cost-text">
                                Safelite price*:
                            </div>
                            <div class="cost">
                            {{ formatAmountInDollars(totalServicePrice) }}
                            </div>
                        </div>
                    </div>
                    <div
                        v-if="showDeductibleOnly"
                        class="d-flex cost cost-underline">
                        {{ formatAmountInDollars(deductibleValue) }}
                    </div>
                    <div
                        class="fw-bold text-black mt-5"
                        v-html="nextStepsHeader"></div>
                    <div
                        class="body-text"
                        v-html="nextStepsBody"></div>
                    <div
                        v-if="isNoCompQuoteVisible"
                        class="no-comp-price-text">
                        Safelite price*:
                    </div>
                    <div
                        v-if="isQuoteDisplayed"
                        class="d-flex justify-content-center cost mb-0 cost-underline">
                        {{ formatAmountInDollars(totalServicePrice) }}
                    </div>
                    <buttonMain
                        ref="buttonMain"
                        class="full-width-button mt-5 mb-5"
                        variant="navigation"
                        :buttonText="buttonText"
                        @clickEvent="navigateForward" />
                    <textLink
                        v-if="isNoCompQuoteVisible || isITACQuoteVisible"
                        class="underlined-text cancel-link mt-5"
                        linkType="text"
                        text="No, I want to cancel"
                        href="#"
                        @clickEvent="cancelClaim" />
                    <textBlock
                        v-if="isDisclaimerVisible"
                        class="mt-5 mb-5"
                        :customText="disclaimerText"
                        typeStyle="caption" />
                    <siteFooter
                        ref="siteFooter"
                        :class="backButtonClass + ' mb-5'"
                        cmsWidgetName="SiteFooterWidget"
                        :isForwardButtonHidden="true"
                        @backClicked="navigateBackByVehicleQuestions" />
                </div>
            </div>
        </div>
        <contentGroupModal
            :ref="RECAL_MODAL_REF_NAME"
            cssModalHeadlineClass="text-center"
            cmsWidgetName="RecalModal" />
    </Form>
</template>

<script>
// Import Component
import { Form } from 'vee-validate';
import siteHeader from '@/iss-components/site-header/site-header.vue';
import contentGroupModal from '@/iss-components/content-group-modal/content-group-modal.vue';
import textBlock from '@/digital-components/text-block/text-block.vue';
import textLink from '@/ux-components/text-link/text-link.vue';
import buttonMain from '@/ux-components/button-main/button-main.vue';
import siteFooter from '@/iss-components/site-footer/site-footer.vue';
// Import Supporting Files
import {
    fetchCmsContentForPage,
    setupModalLink,
    setupModalLinks,
    processIfStatements
} from '@/helpers/cms-content-helper.js';
import settleAllPromises from '@/helpers/layout-helper.js';
import { getDamageString } from '@/helpers/damage-helper.js';
import { useMainStore } from '@/store/index.js';
import vehicleQuestionsMixin from '@/mixins/vehicle-questions-mixin.js';
import baseFormMixin from '@/mixins/base-form-mixin.js';
import navigationScenarios from '@/router/router-constants/navigation-scenarios.js';
import bailoutMessage from '@/constants/bailoutMessage';
import widgetFields from '@/constants/cms-widget-fields.js';
import { formatAmountInDollars, createUnorderedListFromStringOfParagraphs, createOrderedListFromStringOfParagraphs } from '@/helpers/text-helper.js';
import showIssLoadingModal from '@/helpers/loading-modal-helper';
import { getPriceOfLineItems } from '@/helpers/price-calculator';
import coverageStatuses from '@/constants/coverage-statuses';
import coverageType from '@/constants/coverage-type';

const RECAL_MODAL_REF_NAME = 'RecalModal';

export default {
    name: 'coverage-statement',
    components: {
        siteHeader,
        // eslint-disable-next-line vue/no-reserved-component-names
        Form,
        contentGroupModal,
        buttonMain,
        textBlock,
        textLink,
        siteFooter
    },
    mixins: [baseFormMixin, vehicleQuestionsMixin],
    async beforeRouteEnter(to, from, next) {
        const store = useMainStore();

        // Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to?.query?.issPage);
        const getRecalPartsPromise = store.getRecalParts();

        // Settle promises and get results
        const promiseResultMap = [
            {
                resultKey: 'cmsContent',
                promise: cmsContentPromise
            },
            {
                resultKey: 'recalParts',
                promise: getRecalPartsPromise
            }
        ];

        const { isITAC, isDeductible, serviceLocation } = store;
        if (isITAC || isDeductible) {
            promiseResultMap.push({
                resultKey: 'getFinalDeductible',
                promise: store.getFinalDeductible()
            });
        }

        if (!serviceLocation.zipCodeCtu) {
            promiseResultMap.push({
                resultKey: 'validateZip',
                promise: store.validateZip({ zip: store.order.policy.policyZipCode })
            });
        }

        const resultMap = await settleAllPromises(promiseResultMap);

        next(async (vm) => {
            showIssLoadingModal(true);
            vm.setCmsContent(resultMap.cmsContent);
            await vm.initializeComponent();
            if (!vm.unverified) {
                useMainStore().disableKeyFields();
            }
        });
    },
    setup() {
        const mainStore = useMainStore();
        return { mainStore };
    },
    data() {
        return {
            baseServiceLineItems: [],
            widget: {
                disclaimerText: 'DisclaimerWidget',
                subheader: 'SiteSubHeaderWidget',
                explanatoryText: 'ExplanatoryTextWidget',
                nextStep: 'NextStepsWidget'
            },
            RECAL_MODAL_REF_NAME
        };
    },
    computed: {
        coverageStatementSubHeader() {
            return this.getTextFromCmsWithCustomIfStatements(
                this.widget.subheader,
                widgetFields.SUB_HEADER_WIDGET.SUB_HEADER_TEXT
            );
        },
        secondaryText() {
            const itacCostSavings =
                this.deductibleValue - this.totalServicePrice;
            return this.getTextFromCmsWithCustomIfStatements(
                this.widget.subheader,
                widgetFields.SUB_HEADER_WIDGET.SECONDARY_TEXT
            )?.replaceAll(
                '{custom:costSavings}',
                formatAmountInDollars(itacCostSavings)
            );
        },
        disclaimerText() {
            return this.getTextFromCmsWithCustomIfStatements(
                this.widget.disclaimerText,
                widgetFields.TEXT_BLOCK_WIDGET.TEXT
            )?.replaceAll('{custom:disclaimerAmount}', formatAmountInDollars(this.totalServicePrice));
        },
        explanatoryText() {
            return this.getTextFromCmsWithCustomIfStatements(
                this.widget.explanatoryText,
                widgetFields.CONTENT_GROUP_WIDGET.BODY_TEXT
            );
        },
        explanatoryText2() {
            return this.getTextFromCmsWithCustomIfStatements(
                this.widget.explanatoryText,
                widgetFields.CONTENT_GROUP_WIDGET.BODY_TEXT_2
            )?.replaceAll('{custom:currentReplaceDeductible}', formatAmountInDollars(this.mainStore.order.currentDeductible.replace));
        },
        nextStepsHeader() {
            return this.getTextFromCmsWithCustomIfStatements(
                this.widget.nextStep,
                widgetFields.CONTENT_GROUP_WIDGET.HEADER_TEXT
            );
        },
        nextStepsBody() {
            const cmsText = this.getTextFromCmsWithCustomIfStatements(
                this.widget.nextStep,
                widgetFields.CONTENT_GROUP_WIDGET.BODY_TEXT
            )?.replaceAll('{custom:damage}', this.damageText);

            if (this.isITACQuoteVisible || this.isNoCompQuoteVisible) {
                return createUnorderedListFromStringOfParagraphs(cmsText);
            }
            return createOrderedListFromStringOfParagraphs(cmsText);
        },
        damageText() {
            const damageString = getDamageString();
            return damageString === 'match' ? '' : damageString;
        },
        deductibleValue() {
            return this.mainStore.currentDeductible;
        },
        isNoCompQuoteVisible() {
            return this.mainStore.isVerified && this.mainStore.isNoComp;
        },
        isITACQuoteVisible() {
            return this.mainStore.isVerified && this.mainStore.isITAC;
        },
        isDeductibleVisible() {
            return this.mainStore.isVerified && this.mainStore.isDeductible;
        },
        isUnverifiedVisible() {
            return this.mainStore.isUnverified;
        },
        isADAS() {
            const { glassParts } = useMainStore().order.lineItems;
            return (
                glassParts !== null
                && !!glassParts.find((part) => part.requiresRecalibration)
            );
        },
        totalServicePrice() {
            return getPriceOfLineItems(this.baseServiceLineItems);
        },
        isQuoteDisplayed() {
            return this.isNoCompQuoteVisible;
        },
        isDisclaimerVisible() {
            return this.isITACQuoteVisible || this.isNoCompQuoteVisible;
        },
        showDeductibleOnly() {
            return this.isDeductibleVisible && !this.isRepairZeroDeductible;
        },
        shouldRegisterClaim() {
            const {
                vehicle,
                isClaimRegistrationRequired,
                isPolicyLookupSuccessful,
                isPendingClaimRegistration
            } = useMainStore();
            const { policyVehicleId } = vehicle;
            return (
                isPolicyLookupSuccessful
                && policyVehicleId != null
                && policyVehicleId >= 0
                && isClaimRegistrationRequired
                && isPendingClaimRegistration
            );
        },
        isRepair() {
            return this.mainStore.order.damage.isRepair;
        },
        isRepairZeroDeductible() {
            return this.isRepair && this.isDeductibleVisible && this.deductibleValue <= 0;
        },
        buttonText() {
            return (this.isITACQuoteVisible || this.isNoCompQuoteVisible) ? 'Continue scheduling' : 'Continue';
        },
        backButtonClass() {
            if (this.isITACQuoteVisible || this.isNoCompQuoteVisible) {
                return 'centered-back-button';
            }
            return '';
        }
    },
    watch: {
        nextStepsBody(newValue, oldValue) {
            if (newValue !== oldValue) {
                setupModalLink(this, RECAL_MODAL_REF_NAME);
            }
        }
    },
    mounted() {
        setupModalLinks(this);
    },
    methods: {
        arePagePrerequisitesValid() {
            return !!useMainStore().vehicle.carId;
        },
        async initializeComponent() {
            if (this.shouldRegisterClaim) {
                await this.mainStore.registerClaim();
            } else if (!this.mainStore.isClaimRegistrationRequired && this.mainStore.order.insuranceCoverage.coverageType !== coverageType.NONE) {
                this.mainStore.updateCoverageStatus(coverageStatuses.VERIFIED);
            }

            if (this.mainStore.isVerified) {
                await this.getPricedParts();

                // Repairs will never be ITAC
                if (this.isRepair && this.mainStore.isITAC) {
                    this.mainStore.updateCoverageType(coverageType.Deductible);
                }
            }

            showIssLoadingModal(false);
        },
        async getPricedParts() {
            const { glassParts, supportingItems } = this.mainStore.order.lineItems;
            const availableLineItems = [
                ...(glassParts ?? []),
                ...(supportingItems ?? [])
            ];

            // We only call the ITAC pricing endpoint if we are not repair or we are NoComp
            if (!this.isRepair || this.mainStore.isNoComp) {
                const pricingResults = await useMainStore().getITACPriceOrderItems(availableLineItems)
                    .catch((err) => {
                        useMainStore().setBailout(bailoutMessage.pricingResponseError(
                            availableLineItems.map((li) => li.partNumber),
                            {
                                code: err.code,
                                message: err.message,
                                data: err.data
                            }
                        ));
                        this.navigateWithScenario(navigationScenarios.PRICING_LOOKUP_ERROR);
                    });
                this.setBaseServiceLineItems(pricingResults);
            }
        },
        async navigateForward() {
            if (this.isUnverifiedVisible || this.isDeductibleVisible) {
                this.navigateWithScenario(navigationScenarios.CLICKED_FORWARD);
            } else if (this.isITACQuoteVisible || this.isNoCompQuoteVisible) {
                this.mainStore.updateIsSafeliteProvider(true);
                this.navigateWithScenario(navigationScenarios.CLICKED_FORWARD_WITH_SAFELITE);
            } else {
                this.mainStore.setBailout(bailoutMessage.coverageStatementInvalidState());
                this.navigateWithScenario(navigationScenarios.CLICKED_FORWARD_WITH_INVALID_STATE);
            }
        },
        navigateWithScenario(scenario) {
            this.$router.navigate(scenario, this.$route);
        },
        getTextFromCmsWithCustomIfStatements(widgetName, widgetField) {
            const rawText = this.getCmsContent(widgetName, widgetField);
            return processIfStatements(
                rawText,
                'custom',
                this.getCustomValueFromString
            );
        },
        getCustomValueFromString(str) {
            const { isRepair } = useMainStore().damage;
            switch (str) {
                case 'coverageUnverified':
                    return this.isUnverifiedVisible;
                case 'verifiedITAC':
                    return this.isITACQuoteVisible;
                case 'verifiedNoComp':
                    return this.isNoCompQuoteVisible;
                case 'ADASReplace':
                    return !isRepair && this.isADAS && !this.isNoCompQuoteVisible && !this.isITACQuoteVisible;
                case 'nonADASReplace':
                    return !isRepair && !this.isADAS && !this.isNoCompQuoteVisible && !this.isITACQuoteVisible;
                case 'verifiedRepairDeductible':
                    return isRepair && this.isDeductibleVisible;
                case 'verifiedRepairZeroDeductible':
                    return isRepair && this.isDeductibleVisible && this.deductibleValue <= 0;
                case 'verifiedRepairZeroDeductibleReplaceDeductibleOverZero':
                    return isRepair && this.isDeductibleVisible && this.deductibleValue <= 0 && this.mainStore.order.currentDeductible.replace > 0;
                case 'verifiedRepairDeductibleOverZero':
                    return isRepair && this.isDeductibleVisible && this.deductibleValue > 0;
                case 'verifiedReplaceDeductible':
                    return !isRepair && this.isDeductibleVisible;
                case 'verifiedReplaceZeroDeductible':
                    return !isRepair && this.isDeductibleVisible && this.deductibleValue <= 0;
                case 'verifiedReplaceDeductibleOverZero':
                    return !isRepair && this.isDeductibleVisible && this.deductibleValue > 0;
                default:
                    return null;
            }
        },
        setBaseServiceLineItems(lineItems) {
            this.baseServiceLineItems = lineItems;
        },
        formatAmountInDollars,
        cancelClaim() {
            this.mainStore.updateIsSafeliteProvider(false);
            this.mainStore.setBailout(bailoutMessage.RequestCallback());
            this.navigateWithScenario(navigationScenarios.CLICKED_FORWARD_WITH_NON_SAFELITE_SHOP);
        }
    }
};
</script>

<style lang="scss" scoped>
.iss-heritage-container-width {
    .coverage-statement-container {
        position: relative;
        min-height: 1px;
        padding-left: .75rem;
        padding-right: .75rem;
    }
}

.coverage-statement {
    .cost {
        color: $green;
        font-size: 1.675rem;
        font-weight: $font-weight-bold;
        line-height: 2.5rem;
        width: fit-content;
    }
    .cost-underline {
        border-bottom: 4px solid #0c7e47;
    }
    .sub-header {
        line-height: 1.5rem;
        margin-top: 20px;
        margin-bottom: 20px;
    }
    .full-width-button {
        width: 100%;
    }
    .underlined-text {
        text-decoration: underline;
    }
    .cancel-link {
        display: block;
        margin: 24px auto 0 auto;
    }
    .back-link {
        display: inline-block;
        align-items: center;
    }
    :deep(.body-text > ol > ul) {
        list-style-position: outside;
        list-style-type: disc;
        padding-left: 0;
    }
    :deep(ol) {
        padding-left: 1.25rem;
    }
    :deep(li) {
        margin-top: 1px;
        padding-left: 5px;
    }
    :deep(ul) {
        padding: 0;
        padding-left: 1.25rem;
        padding-right: 1.25rem;
        line-height: 1.25rem;

        li {
            margin-top: .5rem;
            padding-left: 5px;
        }
    }
    :deep(p) {
        line-height: 1.5rem;
        margin-bottom: 0.5rem;
        strong {
            color: $black;
        }
    }
    :deep(.body-text) {
        line-height: 1.5rem;
        color: $darker-gray;
        strong {
            color: $black;
            font-weight: 500;
        }
        margin-top: 6px;
        a {
            text-decoration: none;
        }
    }
    :deep(.question-text) {
        margin-top: 1.5rem;
        margin-bottom: 0.5rem;
        font-size: 1rem;
        line-height: 1.5rem;
        & > span {
            text-align: left;
        }
    }
    .button-question {
        :deep(fieldset) {
            div.col:last-child {
                label {
                    margin-bottom: 0;
                }
            }
        }
    }
    .itac-price-container {
        display: flex;
        justify-content: space-around;
        border: solid 1px #cacbcc;
        border-radius: 5px;
        align-items: center;
        font-weight: $font-weight-bold;
        color: $black;
        padding: 10px;
        margin-top: 20px;

        .itac-deductible-value-container {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .itac-cost-container {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .itac-deductible-value {
            font-size: 1.675rem;
            font-weight: $font-weight-normal;
            line-height: 2.5rem;
        }
        .separator {
            width: 1px;
            height: 60px;
            background-color: #cacbcc;
        }
    }
    .no-comp-price-text {
        font-weight: 500;
        color: $black;
    }
    :deep(.line-two) {
        margin-top: 20px;
        display: block;
    }
    :deep(.centered-back-button) {
        footer {
            > div {
                justify-content: center;
                #stacked {
                    display: none;
                }
            }
        }
    }
}

.modal {
    overflow: hidden;
}
</style>
