<template>
  <Form
    ref="theForm"
    v-slot="{ meta }"
    @submit="onSubmit"
    @invalidSubmit="onInvalidSubmit">
    <questionsPageLayout
        ref="questionsPageLayout"
        v-model="selectedAnswers"
        isRequired
        :isMetaValid="meta.valid"
        :alertFewMoreQuestionsHeader="AlertFewMoreQuestionsHeader"
        :alertFewMoreQuestionsCopy="AlertFewMoreQuestionsCopy"
        :questionsData="questionsData"
        :validationRules="rules.optionRequired"
        :index="currentGlassIndex"
        @forwardButtonAction="forwardButtonAction"
        @backClick="navigateBackByVehicleQuestions" />
  </Form>
</template>
<script>
// Import Supporting Files
import { fetchCmsContentForPage } from '@/helpers/cms-content-helper';
import settleAllPromises from '@/helpers/layout-helper';

// Import Component
import baseFormMixin from '@/mixins/base-form-mixin';
import issPageValues from '@/router/router-constants/issPage-values';
import { Form } from 'vee-validate';
import { useMainStore } from '@/store';
import globalRules from '@/constants/global-rules';
import vehicleQuestionsMixin from '@/mixins/vehicle-questions-mixin';
import questionsPageLayout from '@/iss-components/questions-page-layout/questions-page-layout.vue';

export default {
    name: 'capability-questions',
    components: {
        // eslint-disable-next-line vue/no-reserved-component-names
        Form,
        questionsPageLayout
    },
    mixins: [baseFormMixin, vehicleQuestionsMixin],
    async beforeRouteEnter(to, from, next) {
        const cmsContentPromise = fetchCmsContentForPage(to.query.issPage);

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

        const resultMap = await settleAllPromises(promiseResultMap);

        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);
        });
    },
    data() {
        return {
            questionsData: [],
            selectedAnswers: {},
            currentGlassIndex: 0,
            rules: {
                optionRequired: globalRules.OPTION_REQUIRED
            }
        };
    },
    computed: {
        AlertFewMoreQuestionsHeader() {
            return this.getCmsContent('AdditionalPartsQuestionsAlert', 'HeadlineText');
        },
        AlertFewMoreQuestionsCopy() {
            return this.getCmsContent('AdditionalPartsQuestionsAlert', 'BodyText');
        },
        partsOrQuestionsData() {
            return useMainStore().pageData(issPageValues.CAPABILITY_QUESTIONS)
                .partsOrQuestions;
        }
    },
    mounted() {
        this.getInitialQuestionData();
    },
    methods: {
        arePagePrerequisitesValid() {
            const capabilityQuestionsFromPageData = useMainStore().pageData(issPageValues.CAPABILITY_QUESTIONS);
            return (
                capabilityQuestionsFromPageData?.partsOrQuestions?.some((part) => part?.glassName)
                && capabilityQuestionsFromPageData?.partsOrQuestions?.some((part) => part?.capabilityQuestions?.length > 0)
            );
        },
        getInitialQuestionData() {
            // get any questions that were already answered
            const alreadyAnsweredQuestions = useMainStore().damage.capabilityQuestionAnswers;
            this.questionsData = this.partsOrQuestionsData
                .filter((x) => x.capabilityQuestions)
                .map((glass, index) => {
                    // NOTE: questions for property "questions" can differ between layouts
                    glass.questions = glass.capabilityQuestions;
                    glass.answerKey = `${glass.glassLocation}-${glass.glassName}`;
                    // reset selectedAnswers for this glass
                    this.selectedAnswers[glass.answerKey] = [];
                    const updatedGlass = this.setupInitialData(
                        glass,
                        index,
                        alreadyAnsweredQuestions
                    );
                    // Set up watch for each set of glass questions
                    this.$watch(
                        `selectedAnswers.${glass.answerKey}`,
                        (newValue) => {
                            if (newValue && Object.keys(newValue).length > 0) {
                                this.handleAnswerUpdates(newValue, glass.answerKey);
                            }
                        },
                        { deep: true }
                    );
                    return updatedGlass;
                });
        },
        async forwardButtonAction() {
            const questionAnswersArray = this.questionsData.map((glass) => {
                // get answerResult2 of returned answer
                let selectedAnswerResult2;
                glass.questions.forEach((q) => {
                    const idx = q.answers.findIndex((a) => a.answerResult === glass.answerData.answerResult);
                    if (idx !== -1) {
                        selectedAnswerResult2 = q.answers[idx].answerResult2;
                    }
                });
                return {
                    glassLocation: glass.glassLocation,
                    glassName: glass.glassName,
                    result: glass.answerData.answerResult,
                    result1: glass.answerData.answerResult,
                    result2: selectedAnswerResult2,
                    answeredQuestions: glass.answerData.answeredQuestions,
                    isSuppressedPart: glass.isSuppressedPart
                };
            });
            // clear out answerData for future page loads; must occur prior to store save
            this.questionsData.forEach((glass) => {
                glass.answerData = {};
            });
            // save to store as order.damage.moldingQuestionArrays (array)
            await this.mainStore.saveCapabilityQuestionAnswers(questionAnswersArray);
            // get parts from the capabilityQuestionAnswers
            const partsOrQuestions = this.partsOrQuestionsData;
            // eslint-disable-next-line no-restricted-syntax
            for (const answer of questionAnswersArray) {
                partsOrQuestions.find((partOrQuestion) => (
                    partOrQuestion.glassLocation === answer.glassLocation
                        && partOrQuestion.glassName === answer.glassName
                )).parts[0].childParts = [
                    {
                        partNumber: answer.partNum
                    }
                ];
            }
            this.navigateForward(partsOrQuestions, null);
        }
    }
};
</script>
