<template>
    <div class="d-flex flex-column">
        <v-text-field v-bind="$attrs" ref="datePickerRef" :model-value="dateFormattedReadOnly" autocomplete="off"
            :placeholder="placeholder" :rules="rules" style="z-index: 10" @click="openDatePicker" @click:clear.stop="clearDate">
            <template #append-inner>
                <v-icon icon="mdi-calendar" @click.stop="openDatePicker" />
            </template>
        </v-text-field>
        <div class="w-100 d-flex align-end ga-3 hidden-input">
            <input ref="dateInput" type="date" v-model="date" :min="min" />
        </div>
    </div>
</template>

<script setup lang="ts">

const prop = defineProps({
    rules: {
        type: Array as PropType<Array<any>>,
        default: () => []
    },
    placeholder: {
        type: String,
        default: 'DD/MM/YYYY'
    },
    min: {
        type: String,
        default: undefined
    }
})

const date = defineModel<string | null>({ default: null }) // YYYY-MM-DD format

const dateFormattedReadOnly = ref<string | null>(null)

const dateInput = ref<HTMLInputElement | null>(null)
const datePickerRef = ref<HTMLInputElement | null>(null)

const isInitialLoad = ref(true)

function clearDate() {
    date.value = null
    dateFormattedReadOnly.value = null
}

function openDatePicker() {
    setTimeout(() => {
        dateInput.value?.showPicker?.()
    }, 0)
}

function validate() {
    (datePickerRef.value as any)?.validate()
}

function convertToReadableFormat(dateStr: string): string {
    if (!dateStr) return ""
    const dateObj = new Date(dateStr + "T00:00:00")
    if (Number.isNaN(dateObj.getTime())) return ""

    const day = String(dateObj.getDate()).padStart(2, "0")
    const month = String(dateObj.getMonth() + 1).padStart(2, "0")
    const year = String(dateObj.getFullYear())
    return `${day}/${month}/${year}`
}

function handleInitialDate() {
    if (date.value) {
        dateFormattedReadOnly.value = convertToReadableFormat(date.value)
    } else {
        dateFormattedReadOnly.value = null
    }
}

watch(date, (dateVal) => {
    if (isInitialLoad.value) return
    if (!dateVal) {
        dateFormattedReadOnly.value = null
        return
    }
    dateFormattedReadOnly.value = convertToReadableFormat(dateVal)
}, { immediate: false })

watch(date, () => {
    handleInitialDate()
}, { immediate: true })

onMounted(async () => {
    await nextTick()
    isInitialLoad.value = false
    const nativeInput = (datePickerRef.value as any)?.$el?.querySelector('input')
    if (nativeInput) {
        nativeInput.addEventListener('click', (e: MouseEvent) => {
            e.stopPropagation()
            openDatePicker()
        })
    }
})

defineExpose({
    validate
})
</script>

<style scoped>
.hidden-input {
    opacity: 0;
    height: 0;
    width: 1px;
}
</style>
