<template>
    <div class="row">
        <span class="glass-location-text">
            {{ partType }}
        </span>
    </div>
    <template
        v-for="(tint, index) in tintSelectionOptions"
        :key="index">
        <div class="tint-option">
            <div class="tint-option-text">{{ `${partType} - ${tint}` }}</div>
            <span :class="`tint-image ${convertTintToCSSClass(tint)}`"></span>
        </div>
        <buttonQuestion
            id="glass-part-question"
            v-model="selectedPartNumber"
            buttonTypeString="list-button"
            class="radioQuestion"
            :answers="featureListData[tint]"
            :loaderEnabled="false"
            isRequired
            :groupName="replaceAllSpaceWithDash(`${glassLocation}-${glassName}`)"
            :validationRules="partValidationRules" />
    </template>
</template>

<script>
// Components
import buttonQuestion from '@/digital-components/button-question/button-question.vue';

// Supporting files
import { defineRule } from 'vee-validate';
import { required } from '@/helpers/validation-rules';
import errorMessages from '@/constants/error-messages';
import { toTitleCase } from '@/helpers/text-helper';

export default {
    name: 'glass-part-question',
    components: {
        buttonQuestion
    },
    inheritAttrs: false,
    props: {
        glassName: String,
        glassLocation: String,
        colorAnswers: Array,
        modelValue: Object,
        alreadyPopulatedPartsData: {
            type: Array,
            default: () => []
        }
    },
    emits: ['update:modelValue'],
    data() {
        return {
        };
    },
    computed: {
        partValidationRules() {
            const validationRuleName = `${this.glassLocation}-${this.glassName}-part-required`;

            defineRule(validationRuleName, required(`${this.partType} not selected`));
            return validationRuleName;
        },

        tintSelectionOptions() {
            const tintOptions = [];

            Object.keys(this.featureListData).forEach((tintOption) => {
                tintOptions.push(tintOption);
            });

            return tintOptions;
        },

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

        partsForLocation() {
            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;
        },

        // 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, it) => {
                    featureArr.Text = this.toTitleCaseWithExceptions(it.FeatureAnswerText); // Display to User
                    featureArr.Name = it.PartNumber; // Backing Value

                    return featureArr;
                }, {});

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

            return tintMapByColor;
        },

        PartDataFromApi() {
            return this.mainStore.pageData(this.$route.query.issPage) ?? {};
        },

        partType() {
            const type = this.partsForLocation?.[0]?.partType ?? '';
            return toTitleCase(type);
        }
    },
    mounted() {
        this.AutoSelectIfSinglePart();
    },
    methods: {
        updateSelectedPartNumber(partNumber) {
            this.selectedPartNumber = partNumber;
            this.$nextTick(() => {
                const radioInput = document.querySelector(`input[value=${this.selectedPartNumber}]`);
                // Fire a click event on the input so the field is updated
                radioInput?.click();
            });
        },

        AutoSelectIfSinglePart() {
            if (this.partsForLocation?.length > 0) {
                // Check if only a single part is present for the tint and set the v-model if it is.
                if (this.partsForLocation?.length === 1) {
                    // select element with matching partNumber
                    this.updateSelectedPartNumber(this.partsForLocation[0].partNumber);
                }
            }
        },

        replaceAllSpaceWithDash(str) {
            return String(str).replaceAll(' ', '-');
        },
        convertTintToCSSClass(tint) {
            return tint.toLowerCase().replaceAll(' ', '-').replaceAll(',', '');
        },
        toTitleCaseWithExceptions(text) {
            const exceptions = ['side', 'glass', 'dimming', 'BPassenger', 'soundproofing'];
            let temp = toTitleCase(text);
            exceptions.forEach((exception) => {
                const regEx = new RegExp(exception, 'ig');
                temp = temp.replace(regEx, exception);
            });
            return temp;
        }
    }
};
</script>

<style lang="scss" scoped>
.glass-location-text {
    font-weight: $font-weight-bold;
    color: $black;
}
.tint-option {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    position: relative;
    min-height: 2rem;
    margin-top: .5rem;
    margin-bottom: .25rem;
    font-weight: 600;
    color: $black;

    @include media-breakpoint-up(md) {
        justify-content: flex-start;
    }

    .tint-option-text {
        padding-right: 2.5rem;
    }
}
.radioQuestion {
    :deep(.list-button) {
        margin-bottom: 1rem;
    }

    &:not(:last-child) {
        :deep(.form-test-error) {
            display: none;
        }
    }

    &:last-child {
        :deep(.form-test-error) {
            position: absolute;
            margin: -10px 0 10px 10px;
            font-weight: 600;
            > * {
                padding: 0;
            }
        }
    }
}
.tint-image {
    width: 2rem;
    height: 2rem;
    background-repeat: no-repeat;
    background-image: url(~@/assets/img/tints/GlassTint.png);
    position: absolute;
    top: -.25rem;
    right: 1rem;

    @include media-breakpoint-up(md) {
        position: relative;
        top: -.25rem;
        right: 1.5rem;
        float: left;
    }
}
.blue-tint-green-shade {
    background-position: -53px -53px;
}
.blue-tint-blue-shade {
    background-position: -160px -53px;
}
.gray-tint-gray-shade {
    background-position: -267px -53px;
}
.blue-tint {
    background-position: -373px -53px;
}
.gray-tint {
    background-position: -480px -53px;
}
.green-tint-green-shade {
    background-position: -53px -160px;
}
.green-tint-blue-shade {
    background-position: -160px -160px;
}
.green-tint-gray-shade {
    background-position: -267px -160px;
}
.green-tint {
    background-position: -373px -160px;
}
.clear {
    background-position: -480px -160px;
}
.bronze-tint-green-shade {
    background-position: -53px -266px;
}
.bronze-tint-blue-shade {
    background-position: -160px -266px;
}
.bronze-tint-gray-shade {
    background-position: -267px -266px;
}
.bronze-tint-bronze-shade {
    background-position: -373px -266px;
}
.bronze-tint {
    background-position: -480px -266px;
}
.bronze-tint-privacy {
    background-position: -587px -266px;
}
.clear-blue-shade {
    background-position: -53px -373px;
}
.gray-tint-blue-shade {
    background-position: -160px -373px;
}
.blue-tint-gray-shade {
    background-position: -267px -373px;
}
.gray-tint-privacy {
    background-position: -373px -373px;
}
.tinted {
    background-position: -480px -373px;
}
</style>
