<template>
  <Form @submit="onSubmit" @invalid-submit="onInvalidSubmit" ref="theForm"  v-slot="{ meta }" >
      <div class="page-container-grouped-styles">
          <div class="fade-on-route-transition position-relative">
              <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
                                    v-html="coverageStatementSubHeader"
                                    class="text-center text-black">
                                  </h5>
                                  <div
                                    v-html="explanatoryText"
                                    class="body-text text-center mt-4">
                                  </div>
                                  <div
                                    v-html="secondaryText"
                                    class="text-center mt-4 fw-bold text-black">
                                  </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-1">
                                    {{ formattedServicePrice }}
                                  </div>
                                  <div
                                    v-if="verifiedITAC"
                                    class="d-flex justify-content-center mb-4"> 
                                    {{ deductibleText }}&nbsp;
                                    <span class="text-success fw-bold">{{ formattedDeductible }}</span>
                                  </div>
                                  <alert
                                    ref="verifiedITACAlert"
                                    v-if="verifiedITAC"
                                    class="mb-4"
                                    cmsWidgetName="VerifiedITACAlert"
                                    :manualHeadline="verifiedITACAlertHeader"
                                    :manualCopy="verifiedITACAlertBody"
                                    alertClass="alert-success"
                                    v-bind:isDismissible="false">
                                  </alert>
                                  <div
                                    v-html="nextStepsHeader"
                                    class="fw-bold text-black mb-2">
                                  </div>
                                  <div
                                    v-html="nextStepsBody"
                                    class="body-text">
                                  </div>
                                  <buttonQuestion
                                    v-if="displayQuote"
                                    cmsWidgetName="ServiceProviderQuestion"
                                    :questionText="questionText"
                                    :answers="answersFromCms"
                                    buttonTypeString="listButton"
                                    isRequired
                                    v-model="selectedProvider"
                                    validationRules="selection-required"
                                    id="coverage-button-question">
                                  </buttonQuestion>
                              </div>
                              <siteFooter
                                class="mt-5"
                                cmsWidgetName="SiteFooterWidget"
                                :isForwardActionDisabled="!meta.valid"
                                @backClicked="navigateBack"
                                @forwardClicked="forwardButtonAction"
                                ref="siteFooter" />
                          </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 baseFormMixin from '@/mixins/base-form-mixin';
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 siteSubHeader from '@/iss-components/site-sub-header/site-sub-header.vue';
import textBlock from "@/digital-components/text-block/text-block";
import recalModal from '@/layouts/coverage-statement/recal-modal/recal-modal.vue';
import alert from "@/ux-components/alert/alert";
import contentGroupModal from '@/iss-components/content-group-modal/content-group-modal';
import buttonQuestion from "@/digital-components/button-question/button-question";

// Import Supporting Files
import { fetchCmsContentForPage, setupModalLinks } from '@/helpers/cms-content-helper';
import { settleAllPromises } from '@/helpers/layout-helper';
import { getDamageString } from '@/helpers/damage-helper.js';
import { useMainStore } from "@/store";
import vehicleQuestionsMixin from "@/mixins/vehicle-questions-mixin";
import { processIfStatements } from '@/helpers/cms-content-helper';
import { required } from "@/helpers/validation-rules";
import { errorMessages } from "@/constants/error-messages";

// DEFINE VALIDATION RULES
defineRule("selection-required", required(errorMessages.OPTION_REQUIRED));

const store = useMainStore();

export default {
  name: 'coverage-statement',
  mixins: [baseFormMixin, vehicleQuestionsMixin],
  async beforeRouteEnter(to, from, next) {
    // Call APIs
    const cmsContentPromise = fetchCmsContentForPage(to.query.issPage);
    
    const supportingItemsPromise = await store.getSupportingItems();

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

    if (useMainStore().isClaimRegistrationRequired){
      const registerClaimResponse = await useMainStore().registerClaim();
      promiseResultMap.push({
          resultKey: 'registerClaim',
          promise: registerClaimResponse,
      });
    }

    const resultMap = await settleAllPromises(promiseResultMap);

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

    const pricingResults = await store.getPriceOrderItems(availableLineItems);

    // Call the "next" function to complete the transition to this page.
    next((vm) => {
      vm.setCmsContent(resultMap.cmsContent);
      vm.pricedGlassParts = clonedGlassParts;
      vm.supportingItems = resultMap.supportingItems;
      vm.availableLineItems = pricingResults;
    });
  },
  components: {
      siteFooter,
      siteHeader,
      siteSubHeader,
      Form,
      textBlock,
      recalModal,
      alert,
      contentGroupModal,
      buttonQuestion
  },
  mounted() { 
    setupModalLinks(this);
  },
  data() {
    return {
      isVerified: true, // once verification is complete, change to store.order.payment.insuranceCoverage.isVerified
      supportingItems: [],
      pricedGlassParts: [],
      availableLineItems: [],
      selectedProvider: "",
      deductibleText: "Your deductible is:",
    }
  },
  computed: {
    verifiedITACAlertHeader() {
      return this.getCmsContent(
        "VerifiedITACAlert",
        "HeadlineText"
      )
    },
    verifiedITACAlertBody() {
      return this.getCmsContent(
        "VerifiedITACAlert",
        "BodyText"
      ).replaceAll("{custom:costSavings}", this.costSavings);
    },
    coverageStatementSubHeader() {
      const subheader = this.getSubheaderTextFromCms("SiteSubHeaderWidget");
      return subheader;
    },
    secondaryText() {
      const secondaryText = this.getSecondaryTextFromCms("SiteSubHeaderWidget");
      return secondaryText;
    },
    explanatoryText() {
      const explanatoryText = this.getExplantoryTextFromCms("ExplanatoryTextWidget");
      return explanatoryText;
    },
    nextStepsHeader() {
      const header = this.getHeaderTextFromCms("NextStepsWidget");
      return header;
    },
    nextStepsBody() {
      let body = this.getBodyTextFromCms("NextStepsWidget").replaceAll("{custom:damage}", this.damageText);
      return body;
    },
    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() {
      var damageString = getDamageString();
      return damageString == "match" ? "" : damageString;
    },
    vehicleDeductible() {
      if (this.coverageVerified) {
        if (store.order.damage.isRepair) {
          const repairDeductible = store.order.policy.deductible.repair
          return repairDeductible;
        }
        else {
          const replaceDeductible = store.order.policy.deductible.replace;
          return replaceDeductible;
        }
      }
    },
    formattedDeductible() {
      return this.getDeductibleString(this.vehicleDeductible);
    },
    isDeductibleZero() {
      if (this.coverageVerified && this.verifiedDeductible) {
        return this.vehicleDeductible === 0;
      }
    },
    deductibleOverZero() {
      if (this.coverageVerified && this.verifiedDeductible) {
        return !this.isDeductibleZero;
      }
    },
    coverageVerified() {
      return this.isVerified;
    },
    coverageUnverified() {
      return !this.isVerified;
    },
    verifiedNoComp() {
      if (this.coverageVerified) {
        return store.order.policy.noCompensation;
      }
    },
    verifiedITAC() {
      if (this.coverageVerified && !this.verifiedNoComp) {
        if (this.vehicleDeductible > this.totalServicePrice) {
          return true;
        }
      }
    },
    verifiedDeductible() {
      if (this.coverageVerified && !this.verifiedNoComp) {
        if (this.totalServicePrice > this.vehicleDeductible) {
          return true;
        }
      }
    },
    ADASReplace() {
      if (!store.order.damage.isRepair) {
        let parts = store.order.lineItems.glassParts;

        if (parts != null && parts.filter(part => part.requiresRecalibration).length > 0) {
          return true;
        }
      }
    },
    nonADASReplace() {
      if (!store.order.damage.isRepair) {
        return !this.ADASReplace;
      }
    },
    nonADASRepair() {
      if (store.order.damage.isRepair) {
        return true;
      }
    },
    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() {
      if (this.verifiedITAC || this.verifiedNoComp) {
        return true;
      }
    },
  },
  methods: {
    arePagePrerequisitesValid() {
      if (useMainStore().vehicle.vin) {
          return true;
      }
      return false;
    },
    async forwardButtonAction() {
      return await this.navigateForward();

    },
    async navigateForward() {
      if (this.coverageUnverified || this.verifiedDeductible) {
        this.$router.navigate(
            this.navigationScenarios.CLICKED_FORWARD,
            this.$route
        )
      }
      else if (this.verifiedITAC || this.verifiedNoComp) {
        if (this.selectedProvider === "Safelite") {
          this.$router.navigate(
            this.navigationScenarios.CLICKED_FORWARD_WITH_SAFELITE,
            this.$route
          )
        }
        else if (store.issConfig.enableTPAFlow){
          this.$router.navigate(
            this.navigationScenarios.CLICKED_FORWARD_WITH_THIRD_PARTY,
            this.$route
          )
        }
        else {
          this.$router.navigate(
            this.navigationScenarios.CLICKED_FORWARD_WITH_BAILOUT,
            this.$route
          )
        }
      }
    },
    openModalAction(modalName) {
      this.$refs[modalName.args].openModal();
    },
    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.coverageUnverified;
        case 'verifiedDeductible':
          return this.verifiedDeductible;
        case 'verifiedITAC':
          return this.verifiedITAC;
        case 'verifiedNoComp':
          return this.verifiedNoComp;
        case 'ADASReplace':
          return this.ADASReplace;
        case 'nonADASReplace':
          return this.nonADASReplace;
        case 'nonADASRepair':
          return this.nonADASRepair;
        case 'deductibleOverZero':
          return this.deductibleOverZero
        case 'isDeductibleZero':
          return 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) {
      const savings = vehicleDeductible - totalServicePrice;
      return savings;
    }
  },
  watch: {
    selectedProvider() {
      if (this.selectedProvider === "Safelite") {
        this.$refs.siteFooter.updateButtonText('Continue with Safelite');
      }
      else {
        this.$refs.siteFooter.updateButtonText('Continue');
      }
    }
  }
};
</script>

<style lang="scss">
.body-text {
  p {
    font-size: 14px;
    line-height: 24px;
    margin-bottom: 8px;
  }
}

.cost {
  color: $green;
  font-size: 32px;
  font-weight: 300;
  margin-bottom: 24px;
  line-height: 44px;
}

#coverage-button-question {
  .question-text {
    margin-bottom: 8px;
  }
  .question-text > span {
    text-align: left;
    line-height: 24px;
  }
}

.deductible-modal {
  p {
    margin-bottom: 0px;
  }

  .modal-body p:last-child {
    font-size: 16px;
    line-height: 26px;
  }
  
  .my-4 {
    margin-top: 8px !important;
    margin-bottom: 0px !important;
  }

  img.mb-4 {
    margin: 0 !important;
  }
}
</style>
