<template>
    <div
        class="date-picker-popup"
        :class="[(errors && errors.length) || hasError ? 'has-error' : '']">
        <label
            v-if="displayQuestionText"
            :for="inputId"
            :aria-label="questionText"
            class="form-label"
            :class="[
                questionAlignment === 'center' ? 'text-center w-100 mb-5' : '',
                labelBold ? 'label-bold' : '',
            ]"
            v-html="questionText"></label>
        <div class="input-wrapper">
            <VueDatePicker
                v-model="value"
                :menu-id="`${inputId}-menu`"
                :input-class-name="inputClassName"
                :placeholder="placeholderText"
                :formats="formatsConfig"
                :model-type="modelType"
                :time-config="timeConfig"
                :input-attrs="inputAttrs"
                :disabled="isDisabled"
                :min-date="minDate"
                :max-date="maxDate"
                :auto-apply="autoApply"
                :text-input="textInput"
                :prevent-min-max-navigation="preventMinMaxNavigation"
                :teleport="true"
                :aria-labels="{ input: questionText }"
                @update:model-value="onDateChange"
                @blur="onPickerClosed"
                @closed="onPickerClosed" />
        </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 } from "vee-validate";
import { VueDatePicker } from "@vuepic/vue-datepicker";
import "@vuepic/vue-datepicker/dist/main.css";
import { v4 as uuidv4 } from "uuid";

export default {
    name: "date-picker-popup",
    components: {
        VueDatePicker,
    },
    props: {
        customInputId: String,
        modelValue: [String, Date, Object],
        cmsWidgetName: String,
        validationRules: String,
        isRequired: Boolean,
        isDisabled: Boolean,
        hasError: Boolean,
        displayQuestionText: {
            type: Boolean,
            default: true,
        },
        placeholderText: {
            type: String,
            default: "",
        },
        // Display format shown in the input
        format: {
            type: String,
            default: "MM/dd/yyyy",
        },
        // Format used for the v-model value emitted to parent
        modelType: {
            type: String,
            default: "MM/dd/yyyy",
        },
        enableTimePicker: {
            type: Boolean,
            default: false,
        },
        minDate: {
            type: [String, Date],
            default: null,
        },
        maxDate: {
            type: [String, Date],
            default: null,
        },
        autoApply: {
            type: Boolean,
            default: true,
        },
        clearable: {
            type: Boolean,
            default: true,
        },
        textInput: {
            type: Boolean,
            default: false,
        },
        preventMinMaxNavigation: {
            type: Boolean,
            default: false,
        },
        questionAlignment: String,
        labelBold: {
            type: Boolean,
            default: false,
        },
        centerErrorMessage: Boolean,
        addOptionalText: {
            type: Boolean,
            default: false,
        },
    },
    emits: ["update:modelValue", "change", "blur"],
    setup(props) {
        const uuid = uuidv4();
        const inputId = !props.customInputId ? `date-picker-${uuid}` : props.customInputId;

        const initialValue = props.modelValue ?? "";

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

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

        return {
            inputId,
            errorMessage,
            handleBlur,
            handleChange,
            validate,
            meta,
            errors,
        };
    },
    computed: {
        questionText() {
            if (!this.cmsWidgetName) return "";
            const text = this.getCmsContent
                ? this.getCmsContent(this.cmsWidgetName, "BodyText")
                : "";
            return this.addOptionalText ? `${text} (optional)` : text;
        },
        value: {
            get() {
                return this.modelValue;
            },
            set(newValue) {
                this.$emit("update:modelValue", newValue);
            },
        },
        inputClassName() {
            return [
                "form-control",
                (this.errors && this.errors.length) || this.hasError ? "is-invalid" : "",
            ]
                .filter(Boolean)
                .join(" ");
        },
        formatsConfig() {
            return {
                input: this.format,
                preview: this.format,
            };
        },
        timeConfig() {
            return {
                enableTimePicker: this.enableTimePicker,
            };
        },
        inputAttrs() {
            return {
                id: this.inputId,
                name: this.inputId,
                clearable: this.clearable,
            };
        },
    },
    methods: {
        onDateChange(newValue) {
            this.handleChange(newValue);
            this.$emit("change", newValue);
        },
        onPickerClosed() {
            this.handleBlur();
            // handleChange updates the field value AND triggers reactive validation,
            // populating errors/errorMessage. Pass the current modelValue (may be empty).
            this.handleChange(this.modelValue ?? "");
            this.$emit("blur");
        },
    },
    watch: {
        modelValue(newValue) {
            this.handleChange(newValue);
        },
    },
};
</script>

<style lang="scss">
.date-picker-popup {
    label {
        font-family: UrbanistSemibold;
        color: $black;
    }
    .label-bold {
        font-weight: 600;
    }
    .form-label {
        margin-bottom: 0.25rem;
    }
    .center-error-message {
        justify-content: center !important;
    }

    // Match the look-and-feel of textbox-question's input
    .dp__input {
        border: 1px solid $gray-500;
        border-radius: 0.5rem;
        min-height: 3rem;
        padding: 0.75rem 1rem 0.75rem 2.5rem;
        box-shadow: 0 1px 5px 0 rgba(0, 0, 0, 0.2);
        font-family: inherit;

        @include media-breakpoint-up(md) {
            padding: 1rem 1rem 1rem 2.5rem;
            min-height: 3.5rem;
        }

        &::placeholder {
            color: $gray-500;
        }

        &:focus {
            box-shadow: 0 0 0 2.5px $blue;
            border-color: $gray-500;
        }

        &:hover {
            border: 1px solid $gray-500;
            box-shadow: 0 0 0 4px $blue-300;
        }

        &:disabled,
        &.dp__disabled {
            background-color: $gray-100;
        }
    }

    &.has-error .dp__input {
        border-color: $danger;
    }
}

.dp__today {
    background-color: #ffc966 !important;
    color: $black;
}
</style>
