<template>
    <div
        class="textbox-question"
        :class="[
            (errors && errors.length) || hasError ? 'has-error' : '',
            hideInput ? 'hide-input' : '',
        ]">
        <label
            v-if="displayQuestionText"
            :for="inputId"
            :aria-label="questionText"
            class="form-label"
            :class="[
                questionAlignment === 'center' ? 'text-center w-100 mb-5' : '',
                hideInput ? 'hide-input' : '',
            ]"
            v-html="questionText"></label>
        <div
            class="input-wrapper"
            :class="[
                includeSearchIcon ? 'has-search-icon' : '',
                includeImageQuestion ? 'has-camera-icon' : '',
            ]">
            <input
                class="form-control"
                v-model.trim="value"
                v-maska="mask"
                :type="type"
                :ref="inputId"
                :id="inputId"
                :name="inputId"
                :placeholder="placeholderText"
                :aria-disabled="isDisabled"
                :disabled="isDisabled"
                :aria-required="isRequired"
                :aria-label="questionText"
                :class="[
                    hasIcon ? 'has-icon' : '',
                    iconRight ? 'icon-right' : '',
                    cornerStyle === 'rounded' ? 'rounded-pill' : '',
                    hideInput ? 'hide-input' : '',
                ]"
                :validationRules="validationRules"
                @change="handleChange"
                @blur="handleChange"
                :maxlength="maxLength ? maxLength : '999'"
                @focus="$emit('focus', $event.target.value)"
                @keydown="keyDownHandler"
                :autocomplete="autocomplete" />
            <button
                v-if="includeSearchIcon"
                type="submit"
                aria-label="Search button"
                @click="focusSearchInput" />
            <template v-if="includeImageQuestion">
                <template v-if="!isDisabled">
                    <label class="camera-icon-input" v-show="!isImageProcessing">
                        <input
                            type="file"
                            id="vin-input"
                            accept="image/jpeg,image/png"
                            aria-label="Camera icon/button"
                            data-test="image-upload"
                            @change="imageChanged" />
                    </label>
                    <loader
                        v-show="isImageProcessing"
                        loaderColor="blue"
                        class="loading-icon"></loader>
                </template>
            </template>
        </div>
        <div v-show="errorMessage" class="row form-test-error">
            <span
                class="d-inline-flex small mt-1"
                aria-atomic="true"
                aria-live="polite"
                :class="[centerErrorMessage ? 'center-error-message' : '']">
                {{ errorMessage }}
            </span>
        </div>
    </div>
</template>

<script>
import { useField, validate } from "vee-validate";
import loader from "@/ux-components/loader/loader.vue";
import { ref } from "vue";
import { v4 as uuidv4 } from "uuid";

export default {
    name: "textbox-question",
    props: {
        customInputId: String,
        type: {
            type: String,
            default: "text",
        },
        placeholderText: {
            type: String,
            default: "",
        },
        displayQuestionText: {
            type: Boolean,
            default: true,
        },
        modelValue: String,
        isDisabled: Boolean,
        isRequired: Boolean,
        hasIcon: Boolean, // If input has an icon
        iconRight: Boolean, // Place icon on right side of text input, otherwise default is left if hasIcon prop is used
        hasError: Boolean,
        mask: {
            type: String,
            default: "",
        },
        validationRules: String,
        cmsWidgetName: String,
        maxLength: String,
        questionAlignment: String, // Left or center. Left is default.
        cornerStyle: String, // Rounded or square. Square is default.
        includeSearchIcon: Boolean,
        includeImageQuestion: Boolean,
        imageQuestionSubmitHandler: Function,
        maxFileSize: Number,
        hideInput: Boolean,
        centerErrorMessage: Boolean,
        keyDownHandler: Function,
        addOptionalText: {
            type: Boolean,
            default: false,
            isRequired: false,
        },
        autocomplete: String,
    },
    setup(props) {
        const uuid = uuidv4();
        const inputId = !props.customInputId ? `input-${uuid}` : props.customInputId;

        const propsClone = Object.assign({}, props);
        const modelValue = propsClone.modelValue;
        let initialValue;
        let isImageProcessing = ref(false);

        switch (typeof modelValue) {
            case "number":
                initialValue = modelValue;
                break;
            default:
                initialValue = modelValue && modelValue.length > 0 ? modelValue : "";
                break;
        }

        const fieldOptions = {
            type: "text",
            value: modelValue,
            initialValue: initialValue,
        };

        const { errorMessage, handleBlur, handleChange, meta, validate, errors } = useField(
            inputId,
            props.validationRules,
            fieldOptions
        );

        return {
            inputId,
            errorMessage,
            handleBlur,
            handleChange,
            validate,
            meta,
            errors,
            isImageProcessing,
        };
    },
    methods: {
        focusSearchInput() {
            // Focus cursor in input when search icon is clicked
            const field = document.querySelector("input");
            field.focus();
        },
        async imageChanged(e) {
            let file = e.target.files[0];

            if (!this.isImageValid(file)) {
                this.$emit("imageValidityError");
                return;
            }

            this.isImageProcessing = true;

            try {
                this.value = await this.imageQuestionSubmitHandler(file);

                await this.$nextTick();

                document.getElementById(this.inputId).dispatchEvent(new Event("change"));
            } catch (error) {
                this.$emit("imageLookupError");
            }

            this.isImageProcessing = false;
        },

        isImageValid(imageFile) {
            return imageFile && imageFile.size < this.maxFileSize;
        },
    },
    computed: {
        questionText() {
            return this.addOptionalText
                ? this.getCmsContent(this.cmsWidgetName, "QuestionText") + " (optional)"
                : this.getCmsContent(this.cmsWidgetName, "QuestionText");
        },
        value: {
            get: function () {
                return this.modelValue;
            },
            set: function (newValue) {
                this.$emit("update:modelValue", newValue);
            },
        },
    },
    mounted() {
        this.$emit("textboxQuestionEvent.inputIdAssigned", this.inputId);
    },
    watch: {
        async value(newValue) {
            const result = await validate(newValue, this.validationRules); // do a test validation check, without triggering full validation
            if (result.valid) {
                this.handleChange(newValue); // trigger full validation on this field only
            }
        },
    },
    components: {
        loader,
    },
};
</script>

<style lang="scss">
.textbox-question {
    .hide-input {
        display: none;
    }
    .center-error-message {
        justify-content: center !important;
    }
    label {
        color: $black;
        font-weight: 500;
    }
    .input-wrapper {
        position: relative;
        &.has-search-icon {
            button[type="submit"] {
                position: absolute;
                top: 50%;
                transform: translateY(-50%);
                right: 0;
                background-image: url("data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M15.7817 14.7328L11.8252 10.7762C12.8833 9.45005 13.3936 7.76911 13.2513 6.07849C13.1091 4.38788 12.325 2.81587 11.0601 1.6852C9.79515 0.554524 8.14538 -0.0490261 6.44946 -0.00154744C4.75353 0.0459312 3.14012 0.740836 1.94045 1.94051C0.740775 3.14018 0.0458701 4.75359 -0.00160848 6.44952C-0.0490871 8.14545 0.554463 9.79521 1.68514 11.0601C2.81581 12.325 4.38782 13.1091 6.07843 13.2514C7.76905 13.3937 9.44999 12.8834 10.7762 11.8252L14.7349 15.7839C14.8044 15.8527 14.8869 15.907 14.9774 15.9439C15.068 15.9808 15.165 15.9995 15.2628 15.9989C15.3606 15.9983 15.4573 15.9784 15.5475 15.9405C15.6376 15.9025 15.7194 15.8471 15.7881 15.7776C15.8568 15.708 15.9112 15.6256 15.9481 15.535C15.985 15.4444 16.0036 15.3474 16.0031 15.2496C16.0025 15.1518 15.9826 15.0551 15.9446 14.965C15.9067 14.8748 15.8513 14.7931 15.7817 14.7243V14.7328ZM6.63737 11.7913C5.61803 11.7913 4.62157 11.4891 3.77402 10.9228C2.92646 10.3564 2.26587 9.5515 1.87578 8.60975C1.4857 7.668 1.38363 6.63172 1.5825 5.63196C1.78136 4.6322 2.27222 3.71386 2.99301 2.99307C3.7138 2.27229 4.63214 1.78142 5.6319 1.58256C6.63166 1.38369 7.66793 1.48576 8.60969 1.87585C9.55144 2.26593 10.3564 2.92652 10.9227 3.77408C11.489 4.62163 11.7913 5.61809 11.7913 6.63743C11.7896 8.00382 11.2461 9.31376 10.2799 10.2799C9.3137 11.2461 8.00376 11.7897 6.63737 11.7913Z' fill='%231574A1'/%3E%3C/svg%3E%0A");
                background-repeat: no-repeat;
                background-position: center;
                background-color: transparent;
                width: 2.75rem;
                height: 100%;
                border: none;
                display: flex;
                &:hover {
                    cursor: default;
                }
            }
        }
        &.has-camera-icon {
            label {
                &.camera-icon-input {
                    position: absolute;
                    top: 50%;
                    transform: translateY(-50%);
                    right: 1rem;
                    background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 40 36' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M19.9774 16.5228C17.3559 16.5228 15.1864 18.6621 15.1864 21.3476C15.1864 24.0331 17.3107 26.1724 19.9774 26.1724C22.6441 26.1724 24.7684 24.0331 24.7684 21.3476C24.7684 18.6621 22.6441 16.5228 19.9774 16.5228Z' fill='%231574A1'/%3E%3Cpath d='M38.4181 7.23725H29.8701C29.1469 2.64 24.7684 0 19.9774 0C15.1864 0 10.8531 2.64 10.0847 7.23725H1.58192C0.723164 7.23725 0 7.96553 0 8.83035V33.7738C0 34.6387 0.723164 35.3669 1.58192 35.3669H38.4181C39.2768 35.3669 40 34.6387 40 33.7738V8.83035C40 7.96553 39.2768 7.23725 38.4181 7.23725ZM19.9774 29.7683C15.3672 29.7683 11.5706 25.9904 11.5706 21.3021C11.5706 16.6138 15.3672 12.8814 19.9774 12.8814C24.5876 12.8814 28.3842 16.6593 28.3842 21.3476C28.3842 26.0359 24.6328 29.7683 19.9774 29.7683ZM36.565 14.5655H33.0395V11.0152H36.565V14.5655Z' fill='%231574A1'/%3E%3C/svg%3E%0A");
                    background-repeat: no-repeat;
                    background-position: center;
                    width: 1rem;
                    height: 100%;
                    display: flex;
                    border: none;
                    background-color: transparent;
                    &:hover {
                        cursor: pointer;
                    }
                    input[type="file"] {
                        position: absolute;
                        left: -9999px;
                    }
                }
            }

            .loading-icon {
                position: absolute;
                top: 50%;
                transform: translateY(-50%);
                right: 1rem;
            }
        }
    }
    input {
        &.has-icon {
            background-image: url(~@/assets/img/icons/location-pin.svg);
            background-repeat: no-repeat;
            background-position: 0.75rem 50%;
            background-size: 1rem auto;
            padding: 0 0.75rem 0 2.5rem;
            &.icon-right {
                background-position: calc(100% - 0.75rem) 50%;
                padding: 0 2.5rem 0 0.75rem;
            }
        }
    }
    .form-label {
        margin-bottom: 0.25rem;
    }
    .form-control {
        border: 1px solid $gray-500;
        border-radius: 0.5rem;
        min-height: 3rem;
        padding: 0.75rem 1rem;
        @include media-breakpoint-up(md) {
            padding: 1rem;
            min-height: 3.5rem;
        }
        &::placeholder {
            color: $gray-500;
        }
        &:focus {
            box-shadow: 0 0 0 2.5px $blue;
        }
        &:disabled,
        &.disabled {
            background-color: $gray-100;
            &:hover {
                box-shadow: 0 0 0 4px transparent;
                border: 1px solid $gray-500;
            }
        }
        &:hover {
            border: 1px solid $gray-500;
            box-shadow: 0 0 0 4px $blue-300;
        }
    }
    p {
        display: none;
    }
}
</style>
