<template>
    <VueDatePicker ref="datepickerRef" v-model="dateValue" :enable-time-picker="enableTimePicker" :range="range"
        :multi-calendars="multiCalendars" :auto-apply="autoApply" :format="formatFunction" :min-date="minDate"
        :max-date="maxDate" :placeholder="placeholder" @update:model-value="handleUpdate">
        <template #left-sidebar v-if="showSidebar">
            <DateRangeSidebar @change-date="onSidebarChange"></DateRangeSidebar>
        </template>
    </VueDatePicker>
</template>

<script setup>
import { ref, computed } from 'vue'
import VueDatePicker from '@vuepic/vue-datepicker'
import DateRangeSidebar from './left-sidebar.vue'

// Props
const props = defineProps({
    modelValue: {
        type: [Date, Array, String, Number],
        default: null
    },
    enableTimePicker: {
        type: Boolean,
        default: false
    },
    range: {
        type: Boolean,
        default: true
    },
    multiCalendars: {
        type: Boolean,
        default: true
    },
    autoApply: {
        type: Boolean,
        default: true
    },
    format: {
        type: [Function, String],
        default: null
    },
    minDate: {
        type: Date,
        default: null
    },
    maxDate: {
        type: Date,
        default: null
    },
    placeholder: {
        type: String,
        default: 'Chọn ngày...'
    },
    showSidebar: {
        type: Boolean,
        default: true
    }
})

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

// Refs
const datepickerRef = ref(null)

// Computed
const dateValue = computed({
    get() {
        return props.modelValue
    },
    set(value) {
        emit('update:modelValue', value)
    }
})

// Default format function
const defaultFormat = (dates) => {
    if (!dates) return ''

    // Single date
    if (!Array.isArray(dates)) {
        const d = new Date(dates)
        return `${d.getDate()}/${d.getMonth() + 1}/${d.getFullYear()}`
    }

    // Date range
    if (dates.length === 2) {
        const start = dates[0]
        const end = dates[1]
        const dayStart = start.getDate()
        const monthStart = start.getMonth() + 1
        const yearStart = start.getFullYear()
        const dayEnd = end.getDate()
        const monthEnd = end.getMonth() + 1
        const yearEnd = end.getFullYear()

        return `${dayStart}/${monthStart}/${yearStart} - ${dayEnd}/${monthEnd}/${yearEnd}`
    }

    return ''
}

// Format function to use
const formatFunction = computed(() => {
    return props.format || defaultFormat
})

// Methods
const handleUpdate = (value) => {
    emit('update:modelValue', value)
}

const onSidebarChange = (dates) => {
    dateValue.value = dates
    closeMenu()
}

const closeMenu = () => {
    if (datepickerRef.value) {
        datepickerRef.value.closeMenu()
    }
}

// Expose methods for parent components
defineExpose({
    closeMenu
})
</script>

<style scoped>
/* Custom styles if needed */
</style>
