<template>
    <Form
        ref="theForm"
        v-slot="{ meta }"
        @submit="onSubmit"
        @invalidSubmit="onInvalidSubmit">
        <questions-page-layout
            ref="questionsPageLayout"
            v-model="selectedAnswers"
            :isMetaValid="meta.valid"
            :questionsData="questionsData"
            :validationRules="rules.optionRequired"
            :index="currentGlassIndex"
            @forwardButtonAction="forwardButtonAction"
            @backClick="navigateBackByVehicleQuestions" />
    </Form>
</template>

<script>
// Components
import questionsPageLayout from '@/iss-components/questions-page-layout/questions-page-layout.vue';

// Supporting Files
import { fetchCmsContentForPage } from '@/helpers/cms-content-helper';
import settleAllPromises from '@/helpers/layout-helper';
import { useMainStore } from '@/store';
import issPageValues from '@/router/router-constants/issPage-values';
import { Form } from 'vee-validate';
import vehicleQuestionsMixin from '@/mixins/vehicle-questions-mixin';
import BaseFormMixin from '@/mixins/base-form-mixin.js';
import globalRules from '@/constants/global-rules';

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

        // 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 {
            questionsData: [],
            selectedAnswers: {},
            currentGlassIndex: 0,
            rules: {
                optionRequired: globalRules.OPTION_REQUIRED,
            },
        };
    },
    computed: {
        pageData() {
            return useMainStore().pageData(issPageValues.PART_QUESTIONS);
        },
    },
    mounted() {
        // are there alreadyAnsweredQuestions?
        const alreadyAnsweredQuestions =
            useMainStore().damage.partQuestionAnswers;

        this.questionsData = this.pageData.partsOrQuestions
            .filter((x) => x.partQuestions)
            .map((glass, index) => {
                // NOTE: questions for property "questions" can differ between layouts
                glass.questions = glass.partQuestions;
                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;
            });
    },
    methods: {
        arePagePrerequisitesValid() {
            const partQuestionsFromPageData = useMainStore().pageData(
                issPageValues.PART_QUESTIONS
            );
            return (
                partQuestionsFromPageData &&
                Object.keys(partQuestionsFromPageData.partsOrQuestions).length >
                    0
            );
        },
        async forwardButtonAction() {
            const questionAnswersArray = this.questionsData.map((glass) => ({
                glassLocation: glass.glassLocation,
                glassName: glass.glassName,
                result:
                    (glass.answerData && glass.answerData.answerResult) || '',
                answeredQuestions: glass.answerData?.answeredQuestions,
                isSuppressedPart: glass.isSuppressedPart,
            }));

            // clear out answerData for future page loads; must occur prior to store save
            this.questionsData.forEach((glass) => {
                if (glass.answerData) {
                    glass.answerData = {};
                }
            });

            // save to vuex store as order.damage.partQuestionAnswers (array)
            await this.mainStore.savePartQuestionAnswers(questionAnswersArray);

            // call API parts method
            const partsLookup = await this.mainStore.getParts();

            const glassPartsForStore = partsLookup.data.glassPieceParts;

            // TODO KO delete for quote mvp
            this.navigateForward(glassPartsForStore, null);
        },
    },
};
</script>
