<template>
    <Form @submit="onSubmit" @invalid-submit="onInvalidSubmit" ref="theForm">
        <div class="vehicle-parts small-question-text">
            <loadingModal ref="loadingModal" />
            <div class="container-fluid page-container-grouped-styles">
                <div class="row justify-content-center">
                    <div class="col-md-6">
                        <funnelHeader cmsWidgetName="FunnelHeaderWidget" ref="funnelHeader" />
                    </div>
                </div>
                <div class="row justify-content-center">
                    <div class="col-md-6 col-xl-4 mt-4">
                        <funnelSubHeader
                            ref="funnelSubHeader"
                            cmsWidgetName="FunnelSubHeaderWidget" />
                    </div>
                </div>
                <div class="row justify-content-center">
                    <div class="col-md-6 col-xl-4 my-5">
                        <alert
                            class="rounded border-0 shadow-sm"
                            alertClass="alert-warning"
                            cmsWidgetName="AlertWidget"
                            :isDismissible="false" />
                    </div>
                </div>
                <div class="row justify-content-center">
                    <div class="col-md-6 col-xl-4">
                        <div v-for="(item, i) in PartsOrQuestions" :key="i">
                            <!-- Render horizontal lines if there is multi-glass (aka if i > 0) -->
                            <hr v-if="i > 0" />
                            <glassPartQuestion
                                :ref="`${RefPrefix}-${item.glassLocation}-${item.glassName}`"
                                v-model="
                                    selectedGlassParts[item.glassLocation + '-' + item.glassName]
                                "
                                :glassLocation="item.glassLocation"
                                :glassName="item.glassName"
                                :colorAnswers="item.colorAnswers"
                                :alreadyPopulatedPartsData="alreadyPopulatedPartsData" />
                        </div>
                        <navbar
                            cmsWidgetName="FunnelFooterWidget"
                            ref="navbar"
                            :isForwardActionDisabled="isForwardActionDisabled"
                            @back-clicked="navigateBack"
                            @ForwardClicked="forwardButtonAction" />

                        <saveProgressModalQuestion
                            modalWidgetName="SaveProgressModalWidget"
                            pageName="vehicle-parts"
                            v-if="showSaveProgressModal" />
                    </div>
                </div>
            </div>
        </div>
    </Form>
</template>

<script>
// Components
import glassPartQuestion from "@/layouts/vehicle-parts/glass-part-question/glass-part-question";
import funnelHeader from "@/fmg-components/funnel-header/funnel-header";
import funnelSubHeader from "@/fmg-components/funnel-sub-header/funnel-sub-header";
import navbar from "@/fmg-components/nav-bar/nav-bar";
import alert from "@/ux-components/alert/alert";
import loadingModal from "@/fmg-components/loading-modal/loading-modal.vue";
import saveProgressModalQuestion from "@/fmg-components/save-progress-modal-question/save-progress-modal-question";
// Supporting Files
import { fetchCmsContentForPage } from "@/helpers/cms-content-helper";
import { settleAllPromises } from "@/helpers/layout-helper";
import { fmgPageValues } from "@/router/router-constants/fmgPage-values";
import { Form } from "vee-validate";
import store from "@/store";
import vehicleQuestionsMixin from "@/mixins/vehicle-questions-mixin";
import baseMixin from "@/mixins/base-mixin.js";
import { partTypeStrings } from "@/constants/part-type-strings";

export default {
    name: "vehicle-parts",
    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);
        const emailFromStore = store.getters.order?.customer?.emailAddress;
        // Call the "next" function to complete the transition to this page.
        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);
            vm.showSaveProgressModal = !(emailFromStore?.length > 0);

            // Glass Part Question dynamic component
            Object.keys(vm.$refs)
                .filter((r) => r.includes(vm.RefPrefix) && vm.$refs[r][0] !== undefined)
                .forEach((c) =>
                    vm.$refs[c][0].initializeComponent({
                        ColorQuestionWidget: resultMap.cmsContent.ColorQuestionWidget,
                        FeatureQuestionWidget: resultMap.cmsContent.FeatureQuestionWidget,
                    })
                );
            if (store.getters.externalParameterState?.isExternalParameter) {
                baseMixin.methods.ResetExternalParamsAndHideModal();
            }
        });
    },
    data() {
        return {
            selectedGlassParts: {},
            alertWidgetData: Object,
            alreadyPopulatedPartsData: [],
            showSaveProgressModal: null,
        };
    },
    computed: {
        isForwardActionDisabled() {
            return (
                this.selectedGlassPartNumbers.length !== this.PartsFromApi.partsOrQuestions.length
            );
        },
        selectedGlassPartNumbers() {
            // Compile all selected parts from the page.
            const numberArray = [];
            for (let glassPart of Object.values(this.selectedGlassParts)) {
                if (glassPart?.partNumber) {
                    numberArray.push(glassPart.partNumber);
                }
            }
            return numberArray;
        },
        PartsOrQuestions() {
            const partsData = this.PartsFromApi;

            // Map API result data, to vehicle-parts data structure
            const mappedData = partsData.partsOrQuestions.map((g) => {
                return {
                    glassName: g.glassName,
                    glassLocation: g.glassLocation,
                    colorAnswers: g.parts?.reduce((arr, p) => {
                        arr.push({
                            ColorAnswerText: p.color,
                            FeatureAnswers: [
                                {
                                    FeatureAnswerText:
                                        p.description === "" ? p.color : p.description,
                                    PartNumber: p.partNumber,
                                },
                            ],
                        });
                        return arr;
                    }, []),
                };
            });

            return mappedData;
        },

        PartsFromApi() {
            return this.$store.getters.pageData(fmgPageValues.VEHICLE_PARTS);
        },

        RefPrefix() {
            return "partQuestion";
        },
    },
    methods: {
        arePagePrerequisitesValid() {
            // Check if isRepair is populated and if the pageData we need is here (Parts data)
            const vehiclePartsFromPageData = store.getters.pageData(fmgPageValues.VEHICLE_PARTS);
            return (
                store.getters.damage.isRepair != null &&
                vehiclePartsFromPageData?.partsOrQuestions?.some((part) => part?.glassName)
            );
        },
        async forwardButtonAction() {
            const matchedParts = [];

            // Match them to the parts from the API.
            for (let [key, value] of Object.entries(this.PartsFromApi.partsOrQuestions)) {
                for (let [partKey, partValue] of Object.entries(value.parts)) {
                    const currentPart = this.PartsFromApi.partsOrQuestions[key].parts[partKey];

                    const isMatched = this.selectedGlassPartNumbers.some(
                        (p) => p === currentPart.partNumber
                    );

                    if (isMatched) {
                        matchedParts.push({
                            glassLocation: value.glassLocation,
                            glassName: value.glassName,
                            parts: [currentPart],
                        });
                    }
                }
            }
            // If no parts could be matched, throw an error (isForwardActionDisabled is based off of matchedParts)
            if (this.isForwardActionDisabled) {
                this.$refs.navbar.removeLoader();
                throw new Error("Could not match any parts to the selected parts");
            }

            await this.dispatchStoreAction(
                this.storeActions.RESET_MOLDING_AND_CAPABILITY_QUESTIONS_IF_NEEDED,
                matchedParts,
                false
            );

            // Navigate to the next page
            this.navigateForward(matchedParts);
        },

        LoadInitialPartsData() {
            const partsData = this.PartsFromApi;
            this.alreadyPopulatedPartsData =
                this.$store.getters.lineItems.glassParts === null
                    ? []
                    : this.$store.getters.lineItems.glassParts;

            partsData.partsOrQuestions.map((g) => {
                // If the part is already populated, use the value from the store and populate the v-model.
                Object.keys(this.alreadyPopulatedPartsData).forEach((key) => {
                    const partNumber = this.alreadyPopulatedPartsData[key].partNumber;
                    g.parts.forEach((p) => {
                        if (p.partNumber === partNumber) {
                            this.selectedGlassParts[g.glassLocation + "-" + g.glassName] = p;
                        }
                    });
                });
            });
        },
    },
    mounted() {
        this.LoadInitialPartsData();
    },
    components: {
        Form,
        glassPartQuestion,
        funnelHeader,
        funnelSubHeader,
        navbar,
        alert,
        loadingModal,
        saveProgressModalQuestion,
    },
};
</script>

<style lang="scss">
.vehicle-parts {
    label {
        &.list-card {
            height: auto;
        }
    }
    .two-list-card-width {
        width: 100%;
    }
}
</style>
