<template>
    <div class="relative mb-2">
        <label v-if="label" :for="name" class="pb-2 font-bold text-xl ml-1">{{ label }}</label>
        <div class="flex">
            <input type="date" :name="name" v-model="dateInput" :class="'flex-2 p-2 ' + classes + ' ' + errorClassObject()">
            <input type="time" v-model="timeInput" :class="'flex-1 p-2 ' + classes + ' ' + errorClassObject()">
        </div>
        <p class="text-red no-indent m-0" v-text="errorMessage()">Error Here</p>
    </div>
</template>

<script>
export default {
    name: 'DateTimeField',
    props: {
        classes: String,
        label: String,
        name: {
            type: String,
            required: true,
        },
        required: {
            type: Boolean,
            default: false
        },
        selected: String,
        errors: Object,
    },
    data: function () {
        return {
            dateInput: '',
            timeInput: '00:00',
            value: '',
        }
    },
    computed: {
        hasError: function () {
            return this.required && this.errors && this.errors[this.name] && this.errors[this.name].length > 0
        },
        date: function () {
            return this.selected.split(' ')[0]
        },
        time: function () {
            return this.selected.split(' ')[1]
        }
    },
    methods: {
        updateField: function () {
            this.value = this.dateInput + ' ' + this.timeInput
            this.clearErrors(this.date)
            this.$emit('update:field', this.value)
        },
        errorMessage: function () {
            if (this.hasError) {
                return this.errors[this.name][0]
            }
        },
        clearErrors: function () {
            if (this.hasError) {
                this.errors[this.name] = null
            }
        },
        errorClassObject: function () {
            if (this.hasError) {
                return 'border-red'
            }
        }
    },
    watch: {
        date: function () {
            if (this.selected) {
                this.dateInput = this.date
            }
            this.updateField()
        },
        time: function () {
            if (this.selected) {
                this.timeInput = this.time
            }
            this.updateField()
        }
    }
}
</script>

