<template>
    <label
        :class="[buttonWrapperClasses, { 'has-error': errors.length > 0 }]"
        :for="buttonId"
        @focusin="handleFocus"
        @focusout="handleBlur"
        @mousedown.left="handleEventAction('click', $event)">
        <input
            :type="inputType"
            :id="buttonId"
            :key="buttonId"
            :name="groupName"
            :class="inputClasses"
            :aria-required="isRequired"
            :value="value"
            :checked="isChecked"
            @keypress.space="handleEventAction('space', $event)"
            @keypress.enter="handleEventAction('enter', $event)"
            @change="handleEventAction('change', $event)" />

        <slot></slot>
    </label>
</template>

<script>
import { useField } from "vee-validate";
import { toRef } from "vue";
import { queryStrings } from "@/constants/query-strings";
import eventBus from "@/helpers/event-bus/event-bus.js";

export default {
    name: "base-input-button",
    emits: ["change", "inputButtonClicked"],
    model: {
        prop: "modelValue",
        event: "change",
    },
    props: {
        value: {
            type: [String, Number],
            required: true,
        },
        modelValue: {
            type: [Array, String, Number],
            required: true,
        },
        isMultiSelect: Boolean,
        groupName: {
            type: String,
            required: true,
        },
        validationRules: {
            type: String,
            default: "",
        },
        buttonWrapperClasses: [String, Array, Object],
        inputClasses: [String, Array, Object],
        valueToLogType: String,
        selectOnKeypress: {
            type: Boolean,
            default: true,
        },
        isRequired: Boolean,
        lastValuePushedToGa: {
            type: [String, Number],
            required: true,
        },
        // fullName: {
        //     type: String,
        //     default: "",
        //     required: true,
        // },
    },
    data() {
        return {
            valueToEmit: null,
            // lastValuePushedToGa: null,
        };
    },
    mounted() {
        if (this.isChecked) {
            this.handleChange(this.modelValue);
        }
    },
    methods: {
        handleEventAction(eventType, e) {
            // console.log("Handling: ", eventType)

            if (this.isMultiSelect) {
                switch (eventType) {
                    case this.eventTypes.ENTER:
                    case this.eventTypes.CHANGE:
                        this.handleClick(e);
                        // this.dispatchStoreAction(
                        //     gaStoreActions.UPDATE_LAST_FOCUSED_INPUT_GROUP,
                        //     this.groupName,
                        //     false
                        // );

                        // even if it's pushing from here, it needs to keep track
                        // of lastFocusedInputGroupName and such
                        this.pushClickEventToGA();
                        break;
                }
            } else {
                switch (eventType) {
                    case this.eventTypes.CLICK: // TODO KO pushClickEventToGa?
                    case this.eventTypes.ENTER:
                    case this.eventTypes.SPACE:
                        this.handleClick(e);

                        // this.pushClickEventToGAIfReady();
                        break;
                    case this.eventTypes.CHANGE:
                        this.selectOnKeypress
                            ? this.handleClick(e)
                            : this.handleSelectionChange(e);
                        break;
                }

                if (eventType === this.eventTypes.CLICK) {
                    console.log("PUSH FROM RADIO CLICK");
                    this.pushClickEventToGA();
                }
            }

            // this.pushClickEventToGA(eventType);
        },
        handleSelectionChange(e) {
            if (
                this.isMultiSelect &&
                (this.modelValue instanceof Array || this.modelValue == null)
            ) {
                let newValue = this.modelValue ? [...this.modelValue] : [];
                if (!newValue.includes(this.value)) {
                    newValue.push(this.value);
                } else {
                    newValue.splice(newValue.indexOf(this.value), 1);
                }

                this.valueToEmit = newValue;
            } else {
                this.valueToEmit = this.value;
            }

            // this.dispatchStoreAction(
            //     gaStoreActions.UPDATE_CURRENTLY_SELECTED_VALUES,
            //     {
            //         groupName: this.groupName,
            //         value: this.value,
            //     },
            // );

            this.handleChange(this.valueToEmit);
        },
        handleClick(e) {
            this.handleSelectionChange(e);
            console.log("inputButtonClicked");
            this.$emit("inputButtonClicked", {
                selectedAnswers: this.valueToEmit,
                lastValuePushedToGa: this.lastValuePushedToGa,
            });
        },
        onFocusCallbackForRoot() {
            // console.log("onFocusCallbackForRoot: ", {
            //     isValueSelectedOnClick: this.isValueSelectedOnClick,
            //     isChecked: this.isChecked,
            //     value: this.value,
            //     lastValuePushedToGa: this.lastValuePushedToGa,
            // });
            // if (
            //     !this.isValueSelectedOnClick &&
            //     this.isChecked &&
            //     this.lastValuePushedToGa != this.value
            // ) {
            //     console.log("PUSH FROM ROOT CALLBACK");
            //     this.pushClickEventToGA();
            // }

            this.pushClickEventToGA();
        },
        handleFocus(e) {
            // console.log("FOCUS: ", this.groupName);
            // console.log("FOCUS :", {
            //     groupName: this.groupName,
            //     value: this.value,
            // });
            this.$root.handleInputFocus({
                groupName: this.groupName,
            });
        },
        handleBlur(e) {
            // console.log("BLUR: ", this.groupName);
            // console.log("BLUR :", {
            //     groupName: this.groupName,
            //     value: this.value
            // })
            this.$root.handleInputBlur({
                groupName: this.groupName,
                onFocusCallback: this.onFocusCallbackForRoot,
            });
        },
        pushClickEventToGA(eventType) {
            if (this.isMultiSelect || !eventType) {
                console.log("PUSHING: ", this.value);
            } else {
                if (eventType === this.eventTypes.CLICK) {
                    console.log("PUSHING: ", this.value);
                } else {
                    if (
                        this.isChecked &&
                        this.lastValuePushedToGa != this.value
                    ) {
                        console.log("PUSHING: ", this.value);
                    }
                }
            }

            // this.pushEventToGA(
            //     this.$route.query[queryStrings.FMG_PAGE],
            //     this.GaActions.CLICKED,
            //     this.value?.toString(),
            //     true,
            //     this.valueToLogType
            // );
        },

        // handleBlur() {
        //     // this.dispatchStoreAction(
        //     //     gaStoreActions.UPDATE_LAST_FOCUSED_INPUT_GROUP,
        //     //     this.groupName,
        //     //     false
        //     // );
        //     // this.dispatchStoreAction(
        //     //     gaStoreActions.UPDATE_WAS_LAST_FOCUSED_INPUT_MULTISELECT,
        //     //     this.isMultiSelect,
        //     //     false
        //     // );
        // },
        // handleKeyboardNavigation(key) {
        //     this.pushClickEventToGAIfReady(key);
        // },
        // pushClickEventToGAIfReady(event) {
        //     const gaClickInformation = this.$store.getters.gaClickInformation;
        //     const firedGaClickEventValues =
        //         gaClickInformation.firedGaClickEventValues;
        //     const currentlySelectedValues =
        //         gaClickInformation.currentlySelectedValues;
        //     const lastFocusedInputGroup =
        //         gaClickInformation.lastFocusedInputGroup;
        //     const wasLastFocusedInputMultiselect =
        //         gaClickInformation.wasLastFocusedInputMultiselect;

        //     const keyCode = event?.code;
        //     // Keyboard navigation
        //     if (keyCode) {
        //         if (
        //             !wasLastFocusedInputMultiselect &&
        //             currentlySelectedValues[lastFocusedInputGroup] &&
        //             firedGaClickEventValues[lastFocusedInputGroup] !=
        //                 currentlySelectedValues[lastFocusedInputGroup]
        //         ) {
        //             if (keyCode === "Tab") {
        //                 this.pushClickEventToGA(
        //                     currentlySelectedValues[lastFocusedInputGroup]
        //                 );
        //             } else if (keyCode?.includes("Arrow")) {
        //                 if (lastFocusedInputGroup != this.groupName) {
        //                     this.pushClickEventToGA(
        //                         currentlySelectedValues[lastFocusedInputGroup]
        //                     );
        //                 }
        //             }
        //         }
        //     } else {
        //         // Radio click
        //         // this.dispatchStoreAction(
        //         //     gaStoreActions.UPDATE_LAST_FOCUSED_INPUT_GROUP,
        //         //     this.groupName,
        //         //     false
        //         // );

        //         if (
        //             firedGaClickEventValues[this.groupName] !=
        //             currentlySelectedValues[this.groupName]
        //         ) {
        //             this.pushClickEventToGA(
        //                 currentlySelectedValues[this.groupName]
        //             );
        //         }
        //     }
        // },
    },
    computed: {
        isChecked() {
            if (this.isMultiSelect && this.modelValue instanceof Array) {
                return this.modelValue.includes(this.value);
            } else if (!this.isMultiSelect) {
                return this.modelValue == this.value;
            } else {
                return false;
            }
        },
        inputType() {
            return this.isMultiSelect ? "checkbox" : "radio";
        },
        buttonId() {
            return `${this.groupName?.replace(" ", "-")}-${this.value
                .toString()
                ?.replace(" ", "-")}`;
        },
        isValueSelectedOnClick() {
            return this.isMultiSelect || this.selectingInitiatesLoad;
        },
        eventTypes() {
            return {
                CHANGE: "change",
                ENTER: "enter",
                SPACE: "space",
                CLICK: "click",
            };
        },
        // lastValuePushedToGaTest: {
        //     get: () => {
        //         return this.lastValuePushedToGa;
        //     },
        //     set: () => {
        //         this.$emit("valuePushedToGa", this.value);
        //     },
        // },
    },
    setup(props) {
        const inputType = props.isMultiSelect ? "checkbox" : "radio";

        const fieldOptions = {
            type: inputType,
            validateOnValueUpdate: false,
            validateOnMount: false,
        };

        const { handleChange, meta, errors } = useField(
            toRef(props, "groupName"),
            toRef(props, "validationRules"),
            fieldOptions
        );

        return {
            handleChange,
            errors,
            meta,
            fieldOptions, // only need to expose this for unit test purposes
        };
    },
};
</script>

<style lang="scss" scoped>
input {
    opacity: 0;
    height: 0.1px; // NOTE: cannot be zero or Safari can't put focus on it
    width: 0;
}
</style>
