<template>
    <input ref="inputElement" class="form-control">
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue';

interface Props {
    modelValue?: string | null;
}

const props = withDefaults(defineProps<Props>(), {
    modelValue: null,
});

const emit = defineEmits(['update:modelValue']);

const inputElement = ref<HTMLInputElement | null>(null);

onMounted(() => {
    if (inputElement.value) {
        window.$(inputElement.value).datepicker({
            format: 'dd-mm-yyyy',
            autoclose: true,
            clearBtn: true,
        })
        .val(props.modelValue ?? '')
        .trigger('change')
        .on('changeDate', function (this: HTMLInputElement) {
            emit('update:modelValue', this.value);
        });
    }
});

watch(() => props.modelValue, (newValue) => {
    if (inputElement.value) {
        window.$(inputElement.value).val(newValue ?? '').trigger('change');
    }
});

onUnmounted(() => {
    if (inputElement.value) {
        window.$(inputElement.value).off().datepicker('remove');
    }
});
</script>
