<script setup>
import { NDatePicker, NIcon } from 'naive-ui'
import { computed, ref } from 'vue'
import { router } from '@inertiajs/vue3'
import { TbCalendar } from 'vue-icons-plus/tb'
import { formatRussianDateRange } from '../Utils/dateFormatter.js'

const props = defineProps({
    date: {
        type: Array,
        default: null
    }
})

const showCalendar = ref(false)
const isLoading = ref(false)

const currentShiftDate = computed(() => {
    if (!props.date?.[0]) return null
    const d = new Date(props.date[0])
    d.setHours(0, 0, 0, 0)
    return d
})

const formattedShift = computed(() => {
    if (!props.date?.[0] || !props.date?.[1]) return ''
    return formatRussianDateRange(props.date)
})

const pickerValue = computed(() => currentShiftDate.value?.getTime() ?? null)

const isDateDisabled = (ts) => {
    const now = new Date()
    const today9am = new Date()
    today9am.setHours(9, 0, 0, 0)
    const maxShiftStart = now < today9am
        ? new Date(today9am.setDate(today9am.getDate() - 1))
        : today9am
    maxShiftStart.setHours(0, 0, 0, 0)
    return new Date(ts) > maxShiftStart
}

const navigateToShift = (dateMs) => {
    if (!dateMs) return
    const start = new Date(dateMs)
    start.setHours(9, 0, 0, 0)
    const end = new Date(start)
    end.setDate(end.getDate() + 1)

    isLoading.value = true
    router.reload({
        data: { startAt: start.getTime(), endAt: end.getTime() },
        onFinish: () => { isLoading.value = false }
    })
}

const onPickDate = (value) => {
    showCalendar.value = false
    navigateToShift(value)
}
</script>

<template>
    <div class="relative inline-flex items-center">
        <div
            class="font-medium leading-3 cursor-pointer select-none"
            @click="showCalendar = true"
        >
            {{ formattedShift }}
        </div>

        <NDatePicker
            :value="pickerValue"
            v-model:show="showCalendar"
            class="opacity-0 absolute! inset-x-0 bottom-full -translate-y-1/2"
            placement="top-start"
            :is-date-disabled="isDateDisabled"
            input-readonly
            type="date"
            @update:value="onPickDate"
        />

        <div class="cursor-pointer p-2 flex items-center justify-center" @click="showCalendar = true">
            <NIcon size="20"><TbCalendar /></NIcon>
        </div>
    </div>
</template>

<style scoped>
:deep(.n-input) {
    position: absolute;
    pointer-events: none;
}
</style>
