<script setup lang="ts">
import { Head, usePage } from '@inertiajs/vue3';
import { computed, ref } from 'vue';
import { MainService } from '@/Stores/main';
import {
    mdiAccountMultiple,
    mdiDatabaseOutline,
    mdiChartTimelineVariant,
    mdiFinance,
    mdiMonitorCellphone,
    mdiReload,
    mdiChartPie,
    mdiTrendingUp,
} from '@mdi/js';
import LineChart from '@/Components/Charts/LineChart.vue';
import SectionMain from '@/Components/SectionMain.vue';
import CardBoxWidget from '@/Components/CardBoxWidget.vue';
import CardBox from '@/Components/CardBox.vue';
import TableSampleClients from '@/Components/TableSampleClients.vue';
import LayoutAuthenticated from '@/Layouts/LayoutAuthenticated.vue';
import SectionTitleLineWithButton from '@/Components/SectionTitleLineWithButton.vue';
import CardBoxDataset from '@/Components/CardBoxDataset.vue';
import type { User } from '@/Dataset';

const mainService = MainService();

const isLoadingChart = ref(false);

const fillChartData = async () => {
    isLoadingChart.value = true;
    try {
        await mainService.fetchChartData();
    } finally {
        isLoadingChart.value = false;
    }
};

const chartData = computed(() => mainService.graphData);
const authors = computed(() => mainService.authors);
const datasets = computed(() => mainService.datasets);
const datasetBarItems = computed(() => mainService.datasets.slice(0, 5));
const submitters = computed(() => mainService.clients);
const user = computed(() => usePage().props.authUser as User);

// Initialize data
mainService.fetchApi('clients');
mainService.fetchApi('authors');
mainService.fetchApi('datasets');
mainService.fetchChartData();

// Safe role check: authUser or its roles may be absent depending on auth state
const userHasRoles = (roleNames: Array<string>): boolean => {
    return user.value?.roles?.some((role) => roleNames.includes(role)) ?? false;
};

// Greeting that adapts to the time of day
const greeting = computed(() => {
    const h = new Date().getHours();
    if (h < 12) return 'Good morning';
    if (h < 18) return 'Good afternoon';
    return 'Good evening';
});

const today = computed(() =>
    new Date().toLocaleDateString(undefined, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }),
);
</script>

<template>
    <LayoutAuthenticated :showAsideMenu="false">
        <Head title="Dashboard" />

        <SectionMain>
            <!-- Greeting hero -->
<div
    class="reveal relative overflow-hidden rounded-2xl mb-8 p-6 md:p-8 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 text-white shadow-xl ring-1 ring-white/5"
>
    <!-- grüner Akzent-Glow statt weißer Kreise -->
    <div class="absolute -right-10 -top-10 w-48 h-48 rounded-full bg-emerald-500/15 blur-3xl"></div>
    <div class="absolute -left-8 -bottom-12 w-40 h-40 rounded-full bg-green-400/10 blur-3xl"></div>
    <!-- schmale Akzentkante links -->
    <div class="absolute inset-y-0 left-0 w-1 bg-gradient-to-b from-green-400 to-emerald-600"></div>
    <div class="relative">
        <p class="text-sm font-medium text-slate-400">{{ today }}</p>
        <h1 class="mt-1 text-2xl md:text-3xl font-bold tracking-tight">
            {{ greeting }}, <span class="text-green-400">{{ user?.login ?? 'there' }}</span>
        </h1>
        <p class="mt-2 text-sm text-slate-400 max-w-xl">
            Here's an overview of authors, publications and submitters across the repository.
        </p>
    </div>
</div>

            <!-- Stats Grid -->
            <div class="reveal reveal-1 grid grid-cols-1 gap-6 lg:grid-cols-3 mb-8">
                <div class="rounded-xl border-l-4 border-emerald-500 bg-white dark:bg-slate-900/40 shadow-sm hover:shadow-lg hover:-translate-y-1 transition-all duration-300">
                    <CardBoxWidget
                        trend="12%"
                        trend-type="up"
                        color="text-emerald-500"
                        :icon="mdiAccountMultiple"
                        :number="authors.length"
                        label="Authors"
                    />
                </div>
                <div class="rounded-xl border-l-4 border-blue-500 bg-white dark:bg-slate-900/40 shadow-sm hover:shadow-lg hover:-translate-y-1 transition-all duration-300">
                    <CardBoxWidget
                        trend-type="info"
                        color="text-blue-500"
                        :icon="mdiDatabaseOutline"
                        :number="datasets.length"
                        label="Publications"
                    />
                </div>
                <div class="rounded-xl border-l-4 border-purple-500 bg-white dark:bg-slate-900/40 shadow-sm hover:shadow-lg hover:-translate-y-1 transition-all duration-300">
                    <CardBoxWidget
                        trend-type="up"
                        color="text-purple-500"
                        :icon="mdiChartTimelineVariant"
                        :number="submitters.length"
                        label="Submitters"
                    />
                </div>
            </div>

            <!-- Recent Datasets Section -->
            <div v-if="datasetBarItems.length > 0" class="reveal reveal-2 mb-8">
                <SectionTitleLineWithButton :icon="mdiTrendingUp" title="Recent Publications">
                    <span class="text-sm text-gray-500 dark:text-gray-400">Latest {{ datasetBarItems.length }} publications</span>
                </SectionTitleLineWithButton>

                <div class="grid grid-cols-1 gap-4">
                    <CardBoxDataset
                        v-for="(dataset, index) in datasetBarItems"
                        :key="index"
                        :dataset="dataset"
                        class="hover:shadow-md transition-all duration-300"
                    />
                </div>
            </div>

            <!-- Chart Section -->
            <SectionTitleLineWithButton :icon="mdiChartPie" title="Trends Overview" class="reveal reveal-3 mt-8">
                <span class="text-sm text-gray-500 dark:text-gray-400">Publications per month</span>
            </SectionTitleLineWithButton>

            <CardBox
                title="Performance"
                :icon="mdiFinance"
                :header-icon="mdiReload"
                class="reveal reveal-3 mb-6 shadow-lg"
                @header-icon-click="fillChartData"
            >
                <div v-if="isLoadingChart" class="flex items-center justify-center h-96">
                    <div class="flex flex-col items-center gap-3">
                        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
                        <p class="text-sm text-gray-500 dark:text-gray-400">Loading chart data...</p>
                    </div>
                </div>
                <div v-else-if="chartData" class="relative">
                    <line-chart :data="chartData" class="h-96" />
                </div>
                <div v-else class="flex items-center justify-center h-96 text-gray-500 dark:text-gray-400">
                    <p>No chart data available</p>
                </div>
            </CardBox>

            <!-- Admin Section -->
            <template v-if="userHasRoles(['administrator'])">
                <SectionTitleLineWithButton :icon="mdiAccountMultiple" title="Submitters Management" class="mt-8">
                    <span class="text-sm text-gray-500 dark:text-gray-400">Administrator view</span>
                </SectionTitleLineWithButton>

                <CardBox :icon="mdiMonitorCellphone" title="All Submitters" has-table class="shadow-lg">
                    <TableSampleClients />
                </CardBox>
            </template>
        </SectionMain>
    </LayoutAuthenticated>
</template>

<style scoped>
/* Staggered entrance reveal */
@keyframes fade-up {
    from {
        opacity: 0;
        transform: translateY(12px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.reveal {
    animation: fade-up 0.5s ease-out both;
}
.reveal-1 {
    animation-delay: 0.08s;
}
.reveal-2 {
    animation-delay: 0.16s;
}
.reveal-3 {
    animation-delay: 0.24s;
}

@media (prefers-reduced-motion: reduce) {
    .reveal {
        animation: none;
    }
}
</style>