<script setup lang="ts">
import { Head, Link, usePage } from '@inertiajs/vue3';
import { computed, onMounted, ref } from 'vue';
import { MainService } from '@/Stores/main';
import {
    mdiAccountMultiple,
    mdiDatabaseOutline,
    mdiChartTimelineVariant,
    mdiFinance,
    mdiMonitorCellphone,
    mdiReload,
    mdiChartPie,
    mdiTrendingUp,
    mdiShieldCrownOutline,
    mdiClipboardClockOutline,
    mdiAccountCheckOutline,
    mdiLightningBoltOutline,
    mdiHistory,
    mdiAccountCogOutline,
    mdiAccountEditOutline,
    mdiFileDocumentEditOutline,
    mdiMapSearchOutline,
    mdiArrowRight,
} 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';
import { stardust } from '@eidellev/adonis-stardust/client';

const mainService = MainService();

const isLoadingChart = ref(false);
const loadError = ref<string | null>(null);

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

// Single source of truth for chart loading, used by both the initial
// fetch and the manual refresh so the loading state is always shown.
const loadChart = async () => {
    if (isLoadingChart.value) return; // guard against overlapping requests
    isLoadingChart.value = true;
    try {
        await mainService.fetchChartData();
    } finally {
        isLoadingChart.value = false;
    }
};

// Fetch everything once the component is mounted (avoids running during SSR
// and as unhandled top-level side effects). Requests run in parallel.
onMounted(async () => {
    try {
        await Promise.all([
            mainService.fetchApi('clients'),
            mainService.fetchApi('authors'),
            mainService.fetchApi('datasets'),
            loadChart(),
        ]);
    } catch (e) {
        loadError.value = 'Failed to load dashboard data. Please try refreshing.';
    }
});

// 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;
};

const isAdmin = computed(() => userHasRoles(['administrator']));

// Evaluated once at setup — these don't need to be reactive for a dashboard
// that isn't expected to stay open across a time-of-day boundary.
const now = new Date();

const greeting = (() => {
    const h = now.getHours();
    if (h < 12) return 'Good morning';
    if (h < 18) return 'Good afternoon';
    return 'Good evening';
})();

const today = now.toLocaleDateString(undefined, {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric',
});

// ---------------------------------------------------------------------------
// Admin overview
// ---------------------------------------------------------------------------

// Derived from data already in the store. `status` is read defensively; if your
// dataset model doesn't expose it these fall back to 0 — point them at real
// store fields (e.g. a dedicated `mainService.pendingCount`) when available.
const pendingCount = computed(() => mainService.datasets.filter((d: any) => d?.status === 'approved').length);

const adminStats = computed(() => [
    {
        label: 'Active Submitters',
        value: submitters.value.length,
        icon: mdiAccountCheckOutline,
        border: 'border-emerald-500',
        iconColor: 'text-emerald-500',
    },
    {
        label: 'Publications',
        value: datasets.value.length,
        icon: mdiDatabaseOutline,
        border: 'border-blue-500',
        iconColor: 'text-blue-500',
    },
    {
        label: 'Authors',
        value: authors.value.length,
        icon: mdiAccountMultiple,
        border: 'border-purple-500',
        iconColor: 'text-purple-500',
    },
    {
        label: 'Pending Review',
        value: pendingCount.value,
        icon: mdiClipboardClockOutline,
        border: 'border-amber-500',
        iconColor: 'text-amber-500',
    },
]);

// Ziggy's route() throws for unknown names and may be undefined if Ziggy isn't
// installed — resolve safely so a missing route never crashes the dashboard.
const safeRoute = (name: string, params?: any): string => {
    try {
        // @ts-ignore - Ziggy global
        return typeof stardust.route === 'function' ? stardust.route(name, params) : '#';
    } catch {
        return '#';
    }
};

// Adjust the route names below to match your application's named routes.
const quickActions = [
    {
        label: 'Manage Tethys Accounts',
        description: 'View and edit Tethys accounts',
        icon: mdiAccountCogOutline,
        href: safeRoute('settings.user.index'),
    },
    {
        label: 'Manage Tethys Roles',
        description: 'Edit Tethys roles',
        icon: mdiAccountEditOutline,
        href: safeRoute('settings.role.index'),
    },
    {
        label: 'Review Publications',
        description: 'Approve or reject submissions',
        icon: mdiFileDocumentEditOutline,
        href: safeRoute('editor.dataset.list'),
    },
    {
        label: 'Geographic Search',
        description: 'Search datasets by location',
        icon: mdiMapSearchOutline,
        href: safeRoute('apps.map'),
    },
];

type Activity = {
    id: number | string;
    description: string;
    user?: string;
    created_at: string;
};

// Reads from the store if your backend provides it; otherwise renders an empty
// state. Populate via e.g. mainService.fetchApi('activities') in onMounted.
const recentActivity = computed<Activity[]>(() => (mainService as any).activities ?? []);

const relativeTime = (iso: string): string => {
    const then = new Date(iso).getTime();
    if (Number.isNaN(then)) return '';
    const mins = Math.round((Date.now() - then) / 60000);
    if (mins < 1) return 'just now';
    if (mins < 60) return `${mins}m ago`;
    const hrs = Math.round(mins / 60);
    if (hrs < 24) return `${hrs}h ago`;
    const days = Math.round(hrs / 24);
    if (days < 7) return `${days}d ago`;
    return new Date(iso).toLocaleDateString();
};
</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"
            >
                <!-- green accent glow -->
                <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>
                <!-- thin accent edge on the left -->
                <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>

            <!-- Load error banner -->
            <div
                v-if="loadError"
                role="alert"
                class="reveal mb-8 rounded-xl border-l-4 border-red-500 bg-red-50 dark:bg-red-900/20 p-4 text-sm text-red-700 dark:text-red-300"
            >
                {{ loadError }}
            </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 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 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 color="text-purple-500" :icon="mdiChartTimelineVariant" :number="submitters.length" label="Submitters" />
                </div>
            </div>

            <!-- Recent Datasets Section -->
            <div v-if="recentDatasets.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 {{ recentDatasets.length }} publications </span>
                </SectionTitleLineWithButton>

                <div class="grid grid-cols-1 gap-4">
                    <CardBoxDataset
                        v-for="dataset in recentDatasets"
                        :key="dataset.id"
                        :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="loadChart"
            >
                <div v-if="isLoadingChart" role="status" aria-live="polite" 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 ============================== -->
            <template v-if="isAdmin">
                <SectionTitleLineWithButton :icon="mdiShieldCrownOutline" title="Admin Overview" class="mt-10">
                    <span class="text-sm text-gray-500 dark:text-gray-400">Administrator view</span>
                </SectionTitleLineWithButton>

                <!-- Admin KPI cards -->
                <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
                    <div
                        v-for="stat in adminStats"
                        :key="stat.label"
                        class="rounded-xl border-l-4 bg-white dark:bg-slate-900/40 shadow-sm p-4 flex items-center gap-4 transition-all duration-300 hover:shadow-md"
                        :class="stat.border"
                    >
                        <span
                            class="flex h-11 w-11 shrink-0 items-center justify-center rounded-lg bg-gray-50 dark:bg-slate-800"
                            :class="stat.iconColor"
                        >
                            <svg viewBox="0 0 24 24" class="w-6 h-6" fill="currentColor" aria-hidden="true">
                                <path :d="stat.icon" />
                            </svg>
                        </span>
                        <div>
                            <p class="text-2xl font-bold text-gray-800 dark:text-white leading-none">
                                {{ stat.value }}
                            </p>
                            <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ stat.label }}</p>
                        </div>
                    </div>
                </div>

                <!-- Quick actions + Recent activity -->
                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
                    <!-- Quick actions -->
                    <CardBox :icon="mdiLightningBoltOutline" :show-header-icon="false" title="Quick Actions" class="lg:col-span-1 shadow-lg">
                        <div class="grid gap-3">
                            <Link
                                v-for="action in quickActions"
                                :key="action.label"
                                :href="action.href"
                                class="group flex items-center gap-3 rounded-lg border border-gray-100 dark:border-slate-700 p-3 hover:border-emerald-300 dark:hover:border-emerald-700 hover:bg-emerald-50/50 dark:hover:bg-emerald-900/10 transition-colors"
                            >
                                <span
                                    class="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400"
                                >
                                    <svg viewBox="0 0 24 24" class="w-5 h-5" fill="currentColor" aria-hidden="true">
                                        <path :d="action.icon" />
                                    </svg>
                                </span>
                                <span class="min-w-0 flex-1">
                                    <span class="block text-sm font-medium text-gray-800 dark:text-gray-100">
                                        {{ action.label }}
                                    </span>
                                    <span class="block text-xs text-gray-400 truncate">{{ action.description }}</span>
                                </span>
                                <svg
                                    viewBox="0 0 24 24"
                                    class="w-5 h-5 text-gray-300 group-hover:text-emerald-500 group-hover:translate-x-0.5 transition-all"
                                    fill="currentColor"
                                    aria-hidden="true"
                                >
                                    <path :d="mdiArrowRight" />
                                </svg>
                            </Link>
                        </div>
                    </CardBox>

                    <!-- Recent activity feed -->
                    <CardBox :icon="mdiHistory" :show-header-icon="false" title="Recent Activity" class="lg:col-span-2 shadow-lg">
                        <ul
                            v-if="recentActivity.length > 0"
                            class="relative space-y-5 before:absolute before:left-[7px] before:top-1 before:bottom-1 before:w-px before:bg-gray-200 dark:before:bg-slate-700"
                        >
                            <li v-for="item in recentActivity" :key="item.id" class="relative pl-7">
                                <span
                                    class="absolute left-0 top-1 w-3.5 h-3.5 rounded-full bg-emerald-500 ring-4 ring-white dark:ring-slate-900"
                                ></span>
                                <p class="text-sm text-gray-800 dark:text-gray-200">{{ item.description }}</p>
                                <p class="text-xs text-gray-400 mt-0.5">
                                    <span v-if="item.user">{{ item.user }} &middot; </span>
                                    {{ relativeTime(item.created_at) }}
                                </p>
                            </li>
                        </ul>
                        <div v-else class="flex flex-col items-center justify-center py-10 text-center text-gray-400 dark:text-gray-500">
                            <svg viewBox="0 0 24 24" class="w-10 h-10 mb-2 opacity-60" fill="currentColor" aria-hidden="true">
                                <path :d="mdiHistory" />
                            </svg>
                            <p class="text-sm">No recent activity</p>
                        </div>
                    </CardBox>
                </div>

                <!-- Submitters table -->
                <SectionTitleLineWithButton :icon="mdiAccountMultiple" title="Submitters Management" class="mt-8">
                    <span class="text-sm text-gray-500 dark:text-gray-400">All registered submitters</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>
