<template>
    <div class="row">
        <p class="mb-0 color-question-text">{{ colorQuestionText }}</p>
    </div>
    <div class="nested-radio">
        <div class="row mt-2">
            <div class="col">
                <buttonQuestion
                    v-model="selectedTint"
                    :answers="tintSelectionOptions"
                    buttonTypeString="listCard"
                    :isWide="true"
                    altText=""
                    isRequired
                    :groupName="`${glassLocation}-${glassName}`"
                    :validationRules="tintValidationRules">
                    <div class="row mt-2" aria-live="polite">
                        <div class="col">
                            <buttonQuestion
                                v-model="selectedPartNumber"
                                buttonTypeString="radio"
                                class="radioQuestion"
                                :questionText="glassFeatureQuestion"
                                :answers="featureListData[selectedTint]"
                                textPosition="text-start"
                                :loaderEnabled="false"
                                isRequired
                                isSmallQuestionText
                                :groupName="`${glassLocation}-${glassName}-${selectedTint}`"
                                :validationRules="partValidationRules" />
                        </div>
                    </div>
                </buttonQuestion>
            </div>
        </div>
    </div>
</template>

<script>
// Components
import buttonQuestion from "@/digital-components/button-question/button-question";

// Supporting files
import { getTintImage } from "@/constants/tint-mapper";
import { getCustomTransformValue } from "@/constants/dynamictext-mapper";
import { defineRule } from "vee-validate";
import { required } from "@/helpers/validation-rules";
import { errorMessages } from "@/constants/error-messages";

export default {
    name: "glass-part-question",
    inheritAttrs: false,
    data() {
        return {
            glassColorQuestion: "",
            glassFeatureQuestion: "",
            selectedTint: "",
        };
    },
    props: {
        glassName: String,
        glassLocation: String,
        colorAnswers: Array,
        modelValue: Object,
        alreadyPopulatedPartsData: {
            type: Array,
            default: () => [],
        },
    },
    mounted() {
        this.LoadPreselectedValues();
    },
    components: {
        buttonQuestion,
    },
    computed: {
        tintValidationRules() {
            const validationRuleName = `${this.glassLocation}-${this.glassName}-tint-required`;

            defineRule(validationRuleName, required(errorMessages.OPTION_REQUIRED));

            return validationRuleName;
        },
        partValidationRules() {
            const validationRuleName = `${this.glassLocation}-${this.glassName}-part-required`;

            defineRule(validationRuleName, required(errorMessages.OPTION_REQUIRED));
            return validationRuleName;
        },
        colorQuestionText() {
            return getCustomTransformValue(
                this.glassColorQuestion,
                `${this.glassLocation} ${this.glassName}`
            );
        },

        tintSelectionOptions() {
            const tintOptions = Object.keys(this.featureListData).map((tintOption) => {
                const buttonImage = this.getTintSourceImage(this.glassLocation, tintOption);
                return {
                    value: tintOption,
                    buttonLabel: tintOption,
                    buttonImage: buttonImage ? require(`@/assets/img/tints/${buttonImage}`) : null,
                };
            });
            return tintOptions;
        },

        selectedPartNumber: {
            get() {
                return this.modelValue?.partNumber;
            },
            set(newValue) {
                this.$emit(
                    "update:modelValue",
                    this.partsForSelectedTint.filter((part) => part.partNumber == newValue)[0]
                );
            },
        },

        partsForSelectedTint() {
            const matchingGlass = this.PartDataFromApi.partsOrQuestions?.filter(
                (dataForGlassLocationAndName) =>
                    dataForGlassLocationAndName.glassName == this.glassName &&
                    dataForGlassLocationAndName.glassLocation == this.glassLocation
            );
            const matchingGlassParts = matchingGlass?.length == 1 ? matchingGlass[0].parts : [];
            return matchingGlassParts.filter((part) => part.color == this.selectedTint) ?? [];
        },

        // Creates a map of the feature list data in the correct Name/Value
        // format for the button-question component.
        featureListData() {
            const tintMapByColor = this.colorAnswers.reduce((arr, item) => {
                // Create the key
                const itemColor = item.ColorAnswerText;
                arr[itemColor] = arr[itemColor] || [];

                // Map the data to Name/Text object for ButtonQuestion
                const mappedItem = item.FeatureAnswers.reduce((featureArr, item) => {
                    featureArr["Text"] = item.FeatureAnswerText; // Display to User
                    featureArr["Name"] = item.PartNumber; // Backing Value

                    return featureArr;
                }, {});

                // Add onto the final object
                arr[itemColor].push(mappedItem);

                return arr;
            }, {});

            return tintMapByColor;
        },

        PartDataFromApi() {
            return this.$store.getters.pageData(this.$route.query.fmgPage) ?? {};
        },
    },
    methods: {
        // Initialize the component data
        initializeComponent(cmsContent) {
            this.glassColorQuestion = cmsContent.ColorQuestionWidget.QuestionText;
            this.glassFeatureQuestion = cmsContent.FeatureQuestionWidget.QuestionText;
        },

        // Gets tint images based on the glass type, and tint name.
        // Returns an empty string if the src or object is undefined.
        getTintSourceImage(glassLocation, tintColor) {
            const tintSourceObject = getTintImage(glassLocation, tintColor);

            if (tintSourceObject === undefined || tintSourceObject.src == undefined) {
                return "";
            }

            return tintSourceObject.src;
        },

        // Reset selections when tint changes for the same glass to ensure proper selection.
        // Also checks if only a single part is present for the tint.
        ResetTintAndPartSelections() {
            this.selectedPartNumber = null;
            this.AutoSelectIfSinglePart();
        },

        // Check if only a single part is present for the tint and set the v-model if it is.
        AutoSelectIfSinglePart() {
            if (this.partsForSelectedTint?.length == 1) {
                this.selectedPartNumber = this.partsForSelectedTint[0].partNumber;
            }
        },

        // Loads the preselected values from the store.
        LoadPreselectedValues() {
            this.$nextTick(() => {
                if (this.modelValue !== undefined) {
                    // Populate button-question model-value if parts data already exists in VueX
                    this.selectedTint = this.modelValue?.color;
                }
            });
        },
    },
    watch: {
        selectedTint() {
            this.AutoSelectIfSinglePart();
        },
    },
};
</script>

<style lang="scss">
.nested-radio {
    .ui-radio {
        flex-direction: column;
        margin: 0.25rem 0;
    }

    p {
        font-size: 0.875rem;
    }
}

.color-question-text {
    color: $black;
    font-weight: $font-weight-bold;
}
</style>
