<template>
    <div class="damage-location-question">
        <buttonQuestion
            v-model="selectedValues"
            :questionText="questionText"
            isMultiSelect
            :answers="answersToDisplay"
            :groupName="groupName"
            buttonTypeString="listCard"
            :questionTextClasses="['button-question-text-left','select-all-glass-parts']"
            isRequired
            validationRules="damage-location-required" />
    </div>
</template>

<script>
import buttonQuestion from '@/digital-components/button-question/button-question.vue';
import { defineRule } from 'vee-validate';
import { required } from '@/helpers/validation-rules';
import errorMessages from '@/constants/error-messages';

// DEFINE VALIDATION RULES
defineRule('damage-location-required', required(errorMessages.DAMAGE_LOCATION_REQUIRED));

export default {
    name: 'damage-location-question',
    components: {
        buttonQuestion
    },
    props: {
        modelValue: Array,
        groupName: String,
        cmsWidgetName: String
    },
    emits: ['update:modelValue'],
    data() {
        return {
            damageOptions: Object
        };
    },
    computed: {
        questionText() {
            return this.getCmsContent(this.cmsWidgetName, 'QuestionText');
        },
        answersFromCms() {
            return this.getCmsContent(this.cmsWidgetName, 'Answers');
        },
        selectedValues: {
            get() {
                return this.modelValue;
            },
            set(newValue) {
                this.$emit('update:modelValue', newValue);
            }
        },
        damageOptionsMap() {
            return {
                Windshield: true,
                SideDoor:
                    this.damageOptions.driverSideOptions.availableReplacementOptions.length
                    || this.damageOptions.passengerSideOptions.availableReplacementOptions.length,
                RearWindow: this.damageOptions.backGlassOptions.availableReplacementOptions.length
            };
        },
        answersToDisplay() {
            const filteredAnswers = Array.isArray(this.answersFromCms)
                ? this.answersFromCms.filter((ans) => {
                    const name = ans.Name.split('-');
                    return (
                        name[0].toUpperCase() === this.mainStore.vehicle.category
                          && this.damageOptionsMap[name[1]]
                    );
                })
                : [];
            return filteredAnswers.map((ans) => {
                const newName = ans.Name.includes('-') ? ans.Name.split('-')[1] : ans.Name;
                ans.Name = newName;
                return ans;
            });
        }
    },
    methods: {
        initializeComponent(damageOptions) {
            this.damageOptions = damageOptions;
        }
    }
};
</script>
