<script setup>
import AppLayout from "../Layouts/AppLayout.vue";
import { useAuthStore } from "../Stores/auth.js";
import { NH1, NSpace, NP, NFlex } from 'naive-ui'
import StartButton from "../Components/StartButton.vue";
import { computed, ref } from "vue";
import { format, getHours } from "date-fns";
import { ru } from "date-fns/locale";
import { useNow } from "@vueuse/core";
import { TbArticle, TbChartTreemap, TbDoorExit, TbUserCog } from "vue-icons-plus/tb";
import { FcWikipedia } from "vue-icons-plus/fc";
import { useReportStore } from "../Stores/report.js";
import SelectUserModal from "./Report/Components/SelectUserModal.vue";
import { Link } from "@inertiajs/vue3";
import { useServerTime } from "../Composables/useServerTime.js";

const authStore = useAuthStore()
const reportStore = useReportStore()

const { serverTime } = useServerTime()
const now = useNow({ interval: 1000 })

const currentDate = computed(() => {
    const nowTime = serverTime.value

    // Если дата ещё не пришла или невалидна - возвращаем заглушку
    if (!serverTime.value || isNaN(serverTime.value.getTime())) {
        const formatted = format(now.value, 'PPPPpp', { locale: ru })
        return formatted.charAt(0).toUpperCase() + formatted.slice(1)
    }

    const formatted = format(nowTime, 'PPPPpp', { locale: ru })
    return formatted.charAt(0).toUpperCase() + formatted.slice(1)
})

const isLockReportButton = computed(() => {
    const hasPrivilegedRole = authStore.availableRoles?.some(role =>
        ['admin', 'head_of_department'].includes(role.slug)
    )

    if (hasPrivilegedRole) return false

    if (!serverTime.value || isNaN(serverTime.value.getTime())) {
        return true
    }

    const hours = getHours(serverTime.value)

    if (hours >= 6 && hours < 7) return false

    return true
})

const showSelectUserModal = ref(false)
const onShowSelectUserModal = () => {
    if (authStore.isDoctor)
        showSelectUserModal.value = true
}

const reportButtonType = computed(() => authStore.isDoctor ? 'button' : Link)
</script>

<template>
    <AppLayout>
        <div class="flex flex-col justify-start items-center mt-12 max-h-[calc(100vh-96px)] min-h-[calc(100vh-96px)] h-full">
            <NFlex vertical justify="space-between" class="max-w-xl w-full h-full mb-12">
                <NFlex vertical align="center" justify="center" class="max-w-xl w-full">
                    <NSpace vertical align="center">
                        <NH1 class="mb-0! text-center leading-9">
                            Здравствуйте<br>{{ authStore.user.name }}!
                        </NH1>
                        <NP class="mb-4!">
                            {{ currentDate }}
                        </NP>
                    </NSpace>

                    <StartButton v-if="authStore.isAdmin || authStore.isDoctor" title="Заполнить сводную"
                        description="Заполняется ежедневно c 06:00 по 07:00" href="/report" :tag="reportButtonType"
                        @click="onShowSelectUserModal" :icon="TbArticle" :lock="isLockReportButton"
                        lock-message="Будет доступно c 06:00 по 07:00" />
                    <StartButton v-if="authStore.isAdmin || authStore.isHeadOfDepartment"
                        title="Статистика моего отделения"
                        :description="`Ваш профиль в системе: ${authStore.userDepartment.department_type.name_short}`"
                        :href="`/statistic`" :icon="TbChartTreemap" />
                    <StartButton v-if="authStore.isAdmin" title="Панель администратора"
                        description="Управление приложением" href="/admin" :tag="Link" :icon="TbUserCog" />
                    <StartButton title="Документация"
                        description="Правила работы с системой"
                        lock lock-message="В разработке"
                        :href="`/statistic`" :icon="FcWikipedia" />

                </NFlex>

                <StartButton title="Выйти из системы" description="Завершение работы с текущей учетной записью"
                        href="/logout" :icon="TbDoorExit" />
            </NFlex>
        </div>
        <SelectUserModal v-model:show="showSelectUserModal" />
    </AppLayout>
</template>

<style scoped></style>
