<template>
    <transition name="fade">
        <div class="replace-options-question" :class="this.answersToDisplay.length < 2 ? 'd-none' : ''">
            <buttonQuestion
                v-if="isAvailable"
                isWide
                :questionText="questionText"
                isMultiSelect
                :answers="answersToDisplay"
                :groupName="groupName"
                buttonType="listCard"
                v-model="selectedValues"
                validationRules="replace-options-required"
            />
        </div>
    </transition>
</template>

<script>
import buttonQuestion from "@/common-components/button-question/button-question";
import store from "@/store";
import { defineRule } from "vee-validate";

// DEFINE VALIDATION RULES
defineRule("replace-options-required", (value) => {
    if (!value || value.length < 1) {
        return "Please select window";
    }
    return true;
});

export default ({
    name: "replaceOptionsQuestion",
    data(){
        return {
            questionText: String,
            answersFromCms: Array,
            replaceOptions: Array,
        }
    },
    props: {
        isAvailable: Boolean,
        filterByVehicleCategory: Boolean,
        groupName: String,
        modelValue: Array,
    },
    methods: {
        initializeComponent(cmsContent, replaceOptions){
            this.questionText = cmsContent.QuestionText;
            this.answersFromCms = cmsContent.Answers;
            this.replaceOptions = replaceOptions;
        },
    },
    computed: {
        selectedValues: {
            get: function() {
                return this.modelValue;
            },
            set: function(newValue) {
                this.$emit("update:modelValue", newValue);
            }
        },
        answersToDisplay(){
            return  Array.isArray(this.answersFromCms) 
                ? this.answersFromCms.filter(ans => 
                    {
                        const name = ans.Name.split('-');
                        return this.filterByVehicleCategory ? name[0].toUpperCase() === store.getters.vehicle.category && this.replaceOptions.includes(name[1]) : this.replaceOptions.includes(ans.Name);
                    }) 
                : [];
        },
    },
    mounted(){
        if(Array.isArray(this.answersToDisplay) && this.answersToDisplay.length === 1) {
            const newSelectedValues = this.selectedValues;
            newSelectedValues.push(this.answersToDisplay[0].Name);
            this.selectedValues = newSelectedValues;
        }
    },
    components: {
        buttonQuestion,
    }
})
</script>

<style lang="scss" scoped>
    .fade-enter-active,
    .fade-leave-active {
        transition: opacity 0.5s ease;
    }

    .fade-enter-from,
    .fade-leave-to {
        opacity: 0;
    }
</style>
