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

const categories = ref<Category[]>([])
const counts = ref<Record<string, number>>({})
const loading = ref(true)
const error = ref<string | null>(null)

async function load() {
  loading.value = true
  error.value = null
  try {
    const [cats, stats] = await Promise.all([
      api.get<Wrapped<Category>>('/api/categories'),
      api.get<Stats>('/api/stats'),
    ])
    categories.value = cats.data
    counts.value = Object.fromEntries(stats.by_category.map(c => [c.slug, c.count]))
  } catch (e) {
    error.value = e instanceof ApiError ? (e.payload.message ?? e.code) : 'Erreur réseau'
  } finally {
    loading.value = false
  }
}
onMounted(load)

const DIMENSION_LABEL = {
  social: 'Plancher social',
  ecologique: 'Plafond écologique',
  transversal: 'Transversal',
} as const

async function destroy(c: Category) {
  const count = counts.value[c.slug] ?? 0
  if (count > 0) {
    alert(`Impossible de supprimer "${c.name}" : ${count} projet(s) utilise(nt) cette catégorie.\nDéplace-les ou archive-les d'abord.`)
    return
  }
  if (!confirm(`Supprimer la catégorie "${c.name}" ?`)) return
  try {
    await api.delete(`/api/categories/${encodeURIComponent(c.slug)}`)
    categories.value = categories.value.filter(x => x.id !== c.id)
  } catch (e) {
    if (e instanceof ApiError) alert(`Erreur : ${e.payload.message ?? e.code}`)
  }
}
</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">Catégories thématiques du Donut.</p>
    </header>
    <AdminSubNav />

    <div class="mt-6 flex items-center justify-end">
      <RouterLink
        :to="{ name: 'admin-category-new' }"
        class="flex items-center gap-1.5 bg-donut-text text-white rounded-lg px-3.5 py-2 text-sm font-medium hover:bg-black transition-colors"
      >
        <svg viewBox="0 0 24 24" class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
          <path d="M12 5v14M5 12h14" />
        </svg>
        Nouvelle catégorie
      </RouterLink>
    </div>

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

    <div v-else class="mt-4 rounded-xl border border-donut-border bg-donut-surface overflow-hidden">
      <table class="w-full text-sm">
        <thead class="bg-gray-50 border-b border-donut-border text-xs uppercase tracking-wider text-donut-muted">
          <tr>
            <th class="text-left px-4 py-3 font-medium">Catégorie</th>
            <th class="text-left px-4 py-3 font-medium">Dimension</th>
            <th class="text-left px-4 py-3 font-medium">Couleur</th>
            <th class="text-right px-4 py-3 font-medium">Ordre</th>
            <th class="text-right px-4 py-3 font-medium">Projets</th>
            <th class="text-right px-4 py-3 font-medium">Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="c in [...categories].sort((a, b) => a.sort_order - b.sort_order)"
            :key="c.id"
            class="border-t border-donut-border hover:bg-gray-50"
          >
            <td class="px-4 py-3">
              <RouterLink
                :to="{ name: 'admin-category-edit', params: { slug: c.slug } }"
                class="font-medium text-donut-text hover:underline"
              >{{ c.name }}</RouterLink>
              <div v-if="c.description" class="text-xs text-donut-muted truncate max-w-md">{{ c.description }}</div>
            </td>
            <td class="px-4 py-3 text-donut-muted">{{ DIMENSION_LABEL[c.dimension] }}</td>
            <td class="px-4 py-3">
              <div class="flex items-center gap-2">
                <span class="w-5 h-5 rounded-md shrink-0" :style="{ background: c.color_hex }" />
                <code class="text-xs">{{ c.color_hex }}</code>
              </div>
            </td>
            <td class="px-4 py-3 text-right tabular-nums">{{ c.sort_order }}</td>
            <td class="px-4 py-3 text-right tabular-nums">{{ counts[c.slug] ?? 0 }}</td>
            <td class="px-4 py-3 text-right">
              <div class="inline-flex items-center gap-3">
                <RouterLink
                  :to="{ name: 'admin-category-edit', params: { slug: c.slug } }"
                  class="text-donut-text hover:underline text-xs font-medium"
                >Éditer</RouterLink>
                <button
                  type="button"
                  class="text-red-500 hover:text-red-700 text-xs font-medium disabled:opacity-30"
                  :disabled="(counts[c.slug] ?? 0) > 0"
                  :title="(counts[c.slug] ?? 0) > 0 ? 'Catégorie utilisée par des projets' : 'Supprimer'"
                  @click="destroy(c)"
                >Supprimer</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </section>
</template>
