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

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

const props = withDefaults(defineProps<{
    modelValue?: any;
    maxDays?: number;
}>(), {
    maxDays: 14,
});

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

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

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

onUnmounted(() => {
    (window as any).$(inputEl.value).datepicker('destroy');
});

watch(() => props.modelValue, (value) => {
    (window as any).$(inputEl.value).val(value).trigger('change');
});

const setStartDate = (date: Date | string) => {
    const startDate = date instanceof Date ? date : new Date(date);
    const maxEndDate = new Date(startDate);
    maxEndDate.setDate(startDate.getDate() + (props.maxDays - 1));

    (window as any).$(inputEl.value).datepicker('setStartDate', startDate);
    (window as any).$(inputEl.value).datepicker('setEndDate', maxEndDate);

    // Ensure the visual highlighting
    (window as any).$(inputEl.value).datepicker('update', startDate);
};

defineExpose({ setStartDate });
</script>
