<template>
    <Form
      @submit="onSubmit"
      @invalid-submit="onInvalidSubmit"
      ref="theForm"
      v-slot="{ meta }"
    >
        <div class="page-container-grouped-styles capability-questions">
            <loadingModal ref="loadingModal"/>
            <funnelHeader cmsWidgetName="FunnelHeaderWidget" />
            <vehicleBanner cmsWidgetName="VehicleBannerWidget" :displayGenericVehicleImage=false />
            <funnelSubHeader cmsWidgetName="FunnelSubHeaderWidget" />
            <div class="fade-on-route-transition sub-container make-tall">
                <alert
                    ref="alertFewMoreQuestions"
                    class="my-5"
                    alertClass="alert-warning"
                    :manualHeadline="AlertFewMoreQuestionsHeader"
                    :manualCopy="AlertFewMoreQuestionsCopy"
                    v-bind:isDismissible="false"
                />
                <questionChain
                    ref="questionChain"
                    v-model="selectedAnswer"    
                    :questionData="capabilityQuestionsData"
                    :partIndex="i"
                    validationRules="questions-required"
                />
                <funnel-footer
                    ref="funnelFooter"
                    cmsWidgetName="FunnelFooterWidget"
                    :isForwardActionDisabled="!meta.valid"
                    @back-clicked="backButtonAction"
                    @ForwardClicked="forwardButtonAction"
                />
            </div>
        </div>
    </Form>
</template>

<script>
// Components
import funnelHeader from "@/common-components/funnel-header/funnel-header";
import vehicleBanner from "@/common-components/vehicle-banner/vehicle-banner";
import alert from "@/ux-components/alert/alert";
import questionChain from "@/common-components/question-chain/question-chain";
import funnelSubHeader from "@/common-components/funnel-sub-header/funnel-sub-header";
import funnelFooter from "@/common-components/funnel-footer/funnel-footer";
import loadingModal from '@/common-components/loading-modal/loading-modal.vue';

// Supporting Files
import { fetchCmsContentForPage } from "@/helpers/cms-content-helper";
import { settleAllPromises } from "@/helpers/layout-helper";
import store from "@/store";
import { storeActions } from "@/constants/store-actions";
import { fmgPageValues } from "@/router/router-constants/fmgPage-values";
import { Form, defineRule } from "vee-validate";
import { required } from "@/helpers/validation-rules";
import { errorMessages } from "@/constants/error-messages";
import vehicleQuestionsMixin from "@/mixins/vehicle-questions-mixin";
import { damageLocationsSelected } from "@/constants/damage-locations-selected";

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

export default {
    name: "capability-questions",
    mixins: [vehicleQuestionsMixin],
    async beforeRouteEnter(to, from, next) {
        // Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to.query.fmgPage);

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

        const resultMap = await settleAllPromises(promiseResultMap);

        // Call the "next" function to complete the transition to this page.
        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);
        });
    },
    data() {
        return {
            selectedAnswer: [],
            // TODO This shouldn't be an object with property `partQuestions`
            capabilityQuestionsData: {
                partQuestions: store.getters.pageData(fmgPageValues.CAPABILITY_QUESTIONS).capabilityQuestions
            }
        };
    },
    computed: {
        AlertFewMoreQuestionsHeader() {
			return this.getCmsContent("AdditionalPartsQuestionsAlert", "HeadlineText");
		},
        AlertFewMoreQuestionsCopy() {
			return this.getCmsContent("AdditionalPartsQuestionsAlert", "BodyText");
		},
        windshieldPart() {
            return this.pageData.partsOrQuestions.find(x => x.glassLocation === damageLocationsSelected.WINDSHIELD);
        },
        windshieldPartInfo() {
            return this.windshieldPart.parts[0];
        },
        pageData() {
            return this.$store.getters.pageData(fmgPageValues.CAPABILITY_QUESTIONS);
        }
    },
    methods: {
        arePagePrerequisitesValid() {
            const capabilityQuestionsPageData = store.getters.pageData(fmgPageValues.CAPABILITY_QUESTIONS);
            return capabilityQuestionsPageData && Object.keys(capabilityQuestionsPageData).length > 0;
        },
        async forwardButtonAction() {
            const selectedAnswerResult1 = this.selectedAnswer.answerResult;
            const selectedAnswerResult2 = this.pageData.capabilityQuestions[0].answers.find(x => x.answerResult1 === selectedAnswerResult1).answerResult2;

            this.dispatchStoreAction(storeActions.SAVE_CAPABILITY_QUESTION_ANSWERS, {
                glassName: this.windshieldPart.glassName,
                glassLocation: this.windshieldPart.glassLocation,
                result1: selectedAnswerResult1,
                result2: selectedAnswerResult2
            });

            const partFromCapabilityQuestionAnswer = (await this.dispatchStoreAction(storeActions.GET_PART_FROM_CAPABILITY_QUESTION_ANSWER)).data;
            let partsOrQuestions = this.pageData.partsOrQuestions;
            partsOrQuestions.find(partOrQuestion => partOrQuestion.glassLocation === damageLocationsSelected.WINDSHIELD).parts = partFromCapabilityQuestionAnswer;

            this.navigateForward(partsOrQuestions);
        },
    },
    components: {
        funnelHeader,
        vehicleBanner,
        alert,
        questionChain,
        funnelSubHeader,
        funnelFooter,
        loadingModal,
        Form,
    },
};
</script>

<style lang="scss">
  .capability-questions {
      .question-text {
        margin-bottom: .5rem;
        span {
            text-align: left;
        }
    }
  }
</style>
