<template>
  <Form
    ref="theForm"
    v-slot="{ meta }"
    @submit="onSubmit"
    @invalidSubmit="onInvalidSubmit">
      <div class="page-container-grouped-styles">
          <div class="fade-on-route-transition position-relative">
              <loadingModal
                ref="loadingModal"
                :textSlides="loadingText" />
              <siteHeader
                ref="siteHeader"
                cmsWidgetName="SiteHeaderWidget" />
              <div class="select-car">
                  <div class="container-fluid pb-2">
                      <div class="row px-3">
                          <div class="col">
                              <div class="pb-1 mt-4">
                                  <h5
                                    ref="siteSubHeader"
                                    class="text-center text-black"
                                    v-html="coverageStatementSubHeader">
                                  </h5>
                                  <div
                                    ref="explanatoryText"
                                    class="body-text text-center mt-2"
                                    v-html="explanatoryText">
                                  </div>
                                  <div
                                    ref="secondaryText"
                                    class="text-center mt-4 mb-1 fw-bold text-black"
                                    v-html="secondaryText">
                                  </div>
                                  <div
                                    v-if="verifiedDeductible"
                                    class="d-flex justify-content-center cost">
                                    {{ formattedDeductible }}
                                  </div>
                                  <div
                                    v-if="displayQuote"
                                    class="d-flex justify-content-center cost mb-0">
                                    {{ formattedServicePrice }}
                                  </div>
                                  <div
                                    v-if="verifiedITAC"
                                    class="d-flex justify-content-center mb-4 deductible-text">
                                    {{ deductibleText }}&nbsp;
                                    <span class="text-success fw-bold">{{ formattedDeductible }}</span>
                                  </div>
                                  <alert
                                    v-if="verifiedITAC"
                                    ref="verifiedITACAlert"
                                    class="mb-5"
                                    cmsWidgetName="VerifiedITACAlert"
                                    :manualHeadline="verifiedITACAlertHeader"
                                    :manualCopy="verifiedITACAlertBody"
                                    alertClass="alert-success"
                                    :isDismissible="false">
                                  </alert>
                                  <div
                                    class="fw-bold text-black mt-5 mb-2"
                                    v-html="nextStepsHeader">
                                  </div>
                                  <div
                                    class="body-text"
                                    v-html="nextStepsBody">
                                  </div>
                                <buttonQuestion
                                    v-if="displayQuote"
                                    v-model="selectedProvider"
                                    cmsWidgetName="ServiceProviderQuestion"
                                    :questionText="questionText"
                                    :answers="answersFromCms"
                                    groupName="ServiceProviderQuestionOption"
                                    buttonTypeString="listButton"
                                    isRequired
                                    :validationRules="rules.selectionRequired">
                                </buttonQuestion>
                              </div>
                              <siteFooter
                                ref="siteFooter"
                                class="mt-5"
                                cmsWidgetName="SiteFooterWidget"
                                :isForwardActionDisabled="!meta.valid"
                                @backClicked="navigateBack"
                                @forwardClicked="forwardButtonAction" />
                          </div>
                      </div>
                  </div>
              </div>
          </div>
      </div>
      <recalModal
        ref="RecalModal"
        cmsWidgetName="RecalModal" />
      <contentGroupModal
        ref="DeductibleModal"
        cmsWidgetName="DeductibleModal"
        class="deductible-modal" />
  </Form>
</template>
<script>

// Import Component
import { Form, defineRule } from 'vee-validate';
import siteFooter from '@/iss-components/site-footer/site-footer.vue';
import siteHeader from '@/iss-components/site-header/site-header.vue';
import recalModal from '@/layouts/coverage-statement/recal-modal/recal-modal.vue';
import alert from '@/ux-components/alert/alert.vue';
import contentGroupModal from '@/iss-components/content-group-modal/content-group-modal.vue';
import buttonQuestion from '@/digital-components/button-question/button-question.vue';
import loadingModal from '@/iss-components/loading-modal/loading-modal.vue';

// Import Supporting Files
import { fetchCmsContentForPage, setupModalLinks, setupModalLink, 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 globalRules from '@/constants/global-rules.js';
import baseFormMixin from '@/mixins/base-form-mixin.js';
import navigationScenarios from '@/router/router-constants/navigation-scenarios.js';
import routerParams from '@/router/router-constants/router-params';
import { required } from '@/helpers/validation-rules';
import errorMessages from '@/constants/error-messages';

defineRule('option-required', required(errorMessages.OPTION_REQUIRED));

export default {
    name: 'coverage-statement',
    components: {
        siteFooter,
        siteHeader,
        // eslint-disable-next-line vue/no-reserved-component-names
        Form,
        recalModal,
        alert,
        contentGroupModal,
        buttonQuestion,
        loadingModal
    },
    mixins: [baseFormMixin, vehicleQuestionsMixin],
    async beforeRouteEnter(to, from, next) {
        // Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to?.query?.issPage);
        const supportingItemsPromise = await useMainStore().getSupportingItems();

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

        const resultMap = await settleAllPromises(promiseResultMap);
        const clonedGlassParts = useMainStore().order.lineItems.glassParts
            ? JSON.parse(JSON.stringify(useMainStore().order.lineItems.glassParts))
            : [];
        const availableLineItems = [
            ...(resultMap.supportingItems ?? []),
            ...(clonedGlassParts ?? [])
        ];

        const pricingResults = await useMainStore().getPriceOrderItems(availableLineItems);

        // Call the "next" function to complete the transition to this page.
        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);
            vm.setSupportingItems(resultMap.supportingItems);
            // eslint-disable-next-line no-param-reassign
            vm.availableLineItems = pricingResults;
            vm.$refs.loadingModal.showModal();
            vm.initializeComponent(availableLineItems);
        });
    },
    setup() {
        const mainStore = useMainStore();
        return { mainStore };
    },
    data() {
        return {
            availableLineItems: [],
            selectedProvider: '',
            deductibleText: 'Your deductible is',
            // TODO update when design team gives appropriate text
            loadingText: [
                'Connecting to your insurance company',
                'Nearly there',
                'Finishing up'
            ],
            rules: {
                selectionRequired: globalRules.OPTION_REQUIRED
            },
            supportingItems: null
        };
    },
    computed: {
        verifiedITACAlertHeader() {
            return this.getCmsContent(
                'VerifiedITACAlert',
                'HeadlineText'
            );
        },
        verifiedITACAlertBody() {
            return this.getCmsContent(
                'VerifiedITACAlert',
                'BodyText'
            )?.replaceAll('{custom:costSavings}', this.costSavings);
        },
        coverageStatementSubHeader() {
            return this.getSubheaderTextFromCms('SiteSubHeaderWidget');
        },
        secondaryText() {
            return this.getSecondaryTextFromCms('SiteSubHeaderWidget');
        },
        explanatoryText() {
            return this.getExplantoryTextFromCms('ExplanatoryTextWidget');
        },
        nextStepsHeader() {
            return this.getHeaderTextFromCms('NextStepsWidget');
        },
        nextStepsBody() {
            return this.getBodyTextFromCms('NextStepsWidget')?.replaceAll('{custom:damage}', this.damageText);
        },
        continueWithSchedulingBodyText() {
            return this.getCmsContent('continueWithSchedulingCopy', 'BodyText');
        },
        unverifiedADASNextStepsBodyText() {
            return this.getCmsContent('UnverifiedADASNextStepsWidget', 'BodyText')?.replaceAll('{custom:damage}', this.damageText);
        },
        unverifiedNonADASNextStepsBodyText() {
            return this.getCmsContent('UnverifiedNonADASNextStepsWidget', 'BodyText')?.replaceAll('{custom:damage}', this.damageText);
        },
        unverifiedNonADASRepairBodyText() {
            return this.getCmsContent('UnverifiedNonADASRepairWidget', 'BodyText');
        },
        damageText() {
            const damageString = getDamageString();
            return damageString === 'match' ? '' : damageString;
        },
        vehicleDeductible() {
            if (useMainStore().order.damage.isRepair) {
                const repairDeductible = useMainStore().order.policy.deductible.repair;
                return repairDeductible;
            }

            const replaceDeductible = useMainStore().order.policy.deductible.replace;
            return replaceDeductible;
        },
        formattedDeductible() {
            return this.getDeductibleString(this.vehicleDeductible);
        },
        isDeductibleZero() {
            return this.vehicleDeductible === 0;
        },
        policyLookupSuccessful() {
            return useMainStore().order.policy.policyLookupSuccessful;
        },
        registerClaimSuccessful() {
            return useMainStore().payment.insuranceCoverage.isVerified;
        },
        verifiedNoComp() {
            return this.policyLookupSuccessful ? useMainStore().order.policy.noCoverage : false;
        },
        verifiedITAC() {
            return this.policyLookupSuccessful
                && !this.verifiedNoComp
                && this.vehicleDeductible > this.totalServicePrice;
        },
        coveredAndServicePriceAboveOrEqualDeductible() {
            return !this.verifiedNoComp && this.totalServicePrice >= this.vehicleDeductible;
        },
        verifiedDeductible() {
            return useMainStore().isClaimRegistrationRequired
                ? this.registerClaimSuccessful && this.coveredAndServicePriceAboveOrEqualDeductible
                : this.policyLookupSuccessful && this.coveredAndServicePriceAboveOrEqualDeductible;
        },
        unverified() {
            return !this.verifiedDeductible && !this.verifiedITAC && !this.verifiedNoComp;
        },
        isADAS() {
            const parts = useMainStore().order.lineItems.glassParts;
            return parts !== null && !!parts.find((part) => part.requiresRecalibration);
        },
        isRepair() {
            return useMainStore().order.damage.isRepair;
        },
        totalServicePrice() {
            let total = 0;
            this.availableLineItems.forEach((lineItem) => {
                total += this.getTotalLineItemPrice(lineItem);
            });
            return total;
        },
        formattedServicePrice() {
            return this.getServicePriceString(this.totalServicePrice);
        },
        costSavings() {
            const savings = this.getITACCostSavings(this.vehicleDeductible, this.totalServicePrice);
            const formattedSavings = parseFloat(savings).toFixed(2);
            return `$${formattedSavings}`;
        },
        questionText() {
            return this.getCmsContent('ServiceProviderQuestion', 'QuestionText');
        },
        answersFromCms() {
            return this.getCmsContent('ServiceProviderQuestion', 'Answers');
        },
        displayQuote() {
            return this.verifiedITAC || this.verifiedNoComp;
        }
    },
    watch: {
        selectedProvider() {
            if (this.selectedProvider === 'Safelite') {
                this.$refs.siteFooter.updateButtonText('Continue with Safelite');
            } else {
                this.$refs.siteFooter.updateButtonText('Continue');
            }
        },
        nextStepsBody(newValue, oldValue) {
            if (newValue !== oldValue) {
                setupModalLink(this, 'RecalModal');
            }
        }
    },
    mounted() {
        setupModalLinks(this);
    },
    methods: {
        arePagePrerequisitesValid() {
            return !!useMainStore().vehicle.vin;
        },
        async initializeComponent() {
            if (this.policyLookupSuccessful
            && useMainStore().isClaimRegistrationRequired
            && this.coveredAndServicePriceAboveOrEqualDeductible) {
                await useMainStore().registerClaim()?.catch(() => {});
            }
            this.$refs.loadingModal.hideModal();
        },
        async forwardButtonAction() {
            return this.navigateForward();
        },
        async navigateForward() {
            useMainStore().updatePolicyITACFlag(this.verifiedITAC);
            if (this.unverified || this.verifiedDeductible) {
                this.mainStore.saveSupportingItems(this.supportingItems);
                this.$router.navigate(
                    navigationScenarios.CLICKED_FORWARD,
                    this.$route,
                    {},
                    { [routerParams.SAVE_SESSION_SYNCHRONOUS]: true }
                );
            } else if (this.verifiedITAC || this.verifiedNoComp) {
                if (this.selectedProvider === 'Safelite') {
                    this.mainStore.saveSupportingItems(this.supportingItems);
                    this.$router.navigate(
                        navigationScenarios.CLICKED_FORWARD_WITH_SAFELITE,
                        this.$route,
                        {},
                        { [routerParams.SAVE_SESSION_SYNCHRONOUS]: true }
                    );
                } else if (useMainStore().issConfig.enableTPAFlow) {
                    this.$router.navigate(
                        navigationScenarios.CLICKED_FORWARD_WITH_TPA_ENABLED,
                        this.$route,
                        {},
                        { [routerParams.SAVE_SESSION_SYNCHRONOUS]: true }
                    );
                } else {
                    this.$router.navigate(
                        navigationScenarios.CLICKED_FORWARD_WITH_TPA_DISABLED,
                        this.$route,
                        {},
                        { [routerParams.SAVE_SESSION_SYNCHRONOUS]: true }
                    );
                }
            } else {
                this.$router.navigate(
                    navigationScenarios.CLICKED_FORWARD_WITH_INVALID_STATE,
                    this.$route,
                    {},
                    { [routerParams.SAVE_SESSION_SYNCHRONOUS]: true }
                );
            }
        },
        processIfStatements,
        getHeaderTextFromCms(cmsWidgetName) {
            const header = this.getCmsContent(cmsWidgetName, 'HeaderText');
            return this.processIfStatements(header, 'custom', this.getCustomValueFromString);
        },
        getSubheaderTextFromCms(cmsWidgetName) {
            const subHeader = this.getCmsContent(cmsWidgetName, 'SubHeaderText');
            return this.processIfStatements(subHeader, 'custom', this.getCustomValueFromString);
        },
        getBodyTextFromCms(cmsWidgetName) {
            const bodyText = this.getCmsContent(cmsWidgetName, 'BodyText');
            return this.processIfStatements(bodyText, 'custom', this.getCustomValueFromString);
        },
        getSecondaryTextFromCms(cmsWidgetName) {
            const secondaryText = this.getCmsContent(cmsWidgetName, 'SecondaryText');
            return this.processIfStatements(secondaryText, 'custom', this.getCustomValueFromString);
        },
        getExplantoryTextFromCms(cmsWidgetName) {
            const explanatoryText = this.getCmsContent(cmsWidgetName, 'BodyText');
            return this.processIfStatements(explanatoryText, 'custom', this.getCustomValueFromString);
        },
        getCustomValueFromString(str) {
            switch (str) {
                case 'coverageUnverified':
                    return this.unverified;
                case 'verifiedDeductible':
                    return this.verifiedDeductible;
                case 'verifiedITAC':
                    return this.verifiedITAC;
                case 'verifiedNoComp':
                    return this.verifiedNoComp;
                case 'ADASReplace':
                    return !this.isRepair && this.isADAS;
                case 'nonADASReplace':
                    return !this.isRepair && !this.isADAS;
                case 'nonADASRepair':
                    return this.isRepair;
                case 'deductibleOverZero':
                    return this.verifiedDeductible && !this.isDeductibleZero; // TODO what if deductible is negative?
                case 'isDeductibleZero':
                    return this.verifiedDeductible && this.isDeductibleZero;
                default:
                    return null;
            }
        },
        getTotalLineItemPrice(lineItem) {
            return lineItem.kitPrice + lineItem.laborAmount + lineItem.sellingPrice;
        },
        getDeductibleString(deductible) {
            const formattedDeductibleFloat = parseFloat(deductible).toFixed(2);
            return `$${formattedDeductibleFloat}`;
        },
        getServicePriceString(price) {
            const formattedPriceFloat = parseFloat(price).toFixed(2);
            return `$${formattedPriceFloat}`;
        },
        getITACCostSavings(vehicleDeductible, totalServicePrice) {
            return vehicleDeductible - totalServicePrice;
        },
        setSupportingItems(newSupportingItems) {
            this.supportingItems = newSupportingItems;
        }
    }
};
</script>

<style lang="scss" scoped>

.cost {
  color: $green;
  font-size: 2rem;
  font-weight: 300;
  line-height: 2.75rem;
}

.deductible-text {
    line-height: 1.5rem;
}

:deep p {
    line-height: 1.5rem;
    font-size: 0.875rem;
    margin-bottom: 0.5rem;
    strong {
        color: $black;
    }
}

:deep .question-text {
    margin-top: 1.5rem;
    margin-bottom: 0.5rem;
    font-size: 1rem;
    line-height: 1.5rem;
    & > span {
        text-align: left;
    }
}

:deep .deductible-modal {
  p {
    margin-bottom: 0 !important;
    font-size: 1rem;
    line-height: 1.625rem;
  }
  img.mb-4 {
    margin: 0 !important;
  }
  h5 {
    color: black;
  }
  p:last-child {
    margin-top: 0.5rem;
  }
}

</style>
