<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { RouterLink } from 'vue-router'
import { api, ApiError } from '@/api/client'
import type { ActivityEvent, Stats, Wrapped } from '@/types/api'
import AdminSubNav from '@/components/AdminSubNav.vue'
import LoadingState from '@/components/LoadingState.vue'
import ErrorState from '@/components/ErrorState.vue'
import { formatRelative } from '@/utils/formatDate'

const stats = ref<Stats | null>(null)
const activity = ref<ActivityEvent[]>([])
const loading = ref(true)
const error = ref<string | null>(null)

async function load() {
  loading.value = true
  error.value = null
  try {
    const [s, a] = await Promise.all([
      api.get<Stats>('/api/stats'),
      api.get<Wrapped<ActivityEvent>>('/api/activity', { query: { limit: 15 } }),
    ])
    stats.value = s
    activity.value = a.data
  } catch (e) {
    error.value = e instanceof ApiError ? (e.payload.message ?? e.code) : 'Erreur réseau'
  } finally {
    loading.value = false
  }
}
onMounted(load)
</script>

<template>
  <section class="px-10 py-8 max-w-7xl">
    <header class="mb-6">
      <h1 class="text-3xl font-semibold text-donut-text">Administration</h1>
      <p class="text-donut-muted mt-1">Vue d'ensemble du Donut Infolab — gestion des projets, membres et catégories.</p>
    </header>
    <AdminSubNav />

    <LoadingState v-if="loading" class="mt-8" />
    <ErrorState v-else-if="error" :message="error" :retry="load" class="mt-8" />

    <div v-else class="mt-8 space-y-6">
      <!-- KPI -->
      <div class="grid grid-cols-2 sm:grid-cols-4 gap-4">
        <RouterLink
          v-for="kpi in [
            { label: 'Projets actifs',     value: stats?.projects_active     ?? 0, to: '/admin/projects', color: '#F97316' },
            { label: 'Projets réalisés',   value: stats?.projects_completed  ?? 0, to: '/admin/projects', color: '#A855F7' },
            { label: 'Archives',           value: stats?.projects_archived   ?? 0, to: '/admin/projects', color: '#6B7280' },
            { label: 'Participants',       value: stats?.participants_total  ?? 0, to: '/admin/members',  color: '#EF4444' },
          ]"
          :key="kpi.label"
          :to="kpi.to"
          class="rounded-xl border border-donut-border bg-donut-surface p-5 hover:shadow-md transition-shadow"
        >
          <div class="flex items-center gap-2">
            <span class="w-2 h-2 rounded-full" :style="{ background: kpi.color }" />
            <div class="text-sm text-donut-muted">{{ kpi.label }}</div>
          </div>
          <div class="mt-2 text-3xl font-semibold text-donut-text tabular-nums">{{ kpi.value }}</div>
        </RouterLink>
      </div>

      <!-- Répartition par catégorie -->
      <div class="rounded-xl border border-donut-border bg-donut-surface p-5">
        <h2 class="text-base font-semibold text-donut-text mb-3">Répartition des projets par catégorie</h2>
        <ul class="space-y-2">
          <li v-for="c in stats?.by_category" :key="c.slug" class="flex items-center gap-3">
            <span class="w-2.5 h-2.5 rounded-full shrink-0" :style="{ background: c.color_hex }" />
            <RouterLink
              :to="{ name: 'projects', query: { category: c.slug } }"
              class="flex-1 text-sm text-donut-text hover:underline truncate"
            >{{ c.name }}</RouterLink>
            <span class="text-sm text-donut-muted tabular-nums">{{ c.count }} projet{{ c.count > 1 ? 's' : '' }}</span>
          </li>
        </ul>
      </div>

      <!-- Flux d'activité -->
      <div class="rounded-xl border border-donut-border bg-donut-surface p-5">
        <h2 class="text-base font-semibold text-donut-text mb-3">Activité récente</h2>
        <ul v-if="activity.length" class="space-y-2.5">
          <li v-for="a in activity" :key="a.id" class="flex items-start gap-3 text-sm">
            <span class="mt-1.5 w-2 h-2 rounded-full bg-status-active shrink-0" aria-hidden="true" />
            <div class="flex-1 min-w-0">
              <span class="text-donut-text">{{ a.summary }}</span>
              <span class="text-donut-muted text-xs ml-2">— {{ formatRelative(a.occurred_at) }}</span>
            </div>
          </li>
        </ul>
        <p v-else class="text-sm text-donut-muted">Aucune activité récente.</p>
      </div>
    </div>
  </section>
</template>
