<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { RouterLink } from 'vue-router'
import { api, ApiError } from '@/api/client'
import type { Category, Paginated, ProjectListRow, ProjectStatus, Wrapped } from '@/types/api'
import AdminSubNav from '@/components/AdminSubNav.vue'
import LoadingState from '@/components/LoadingState.vue'
import ErrorState from '@/components/ErrorState.vue'
import StatusBadge from '@/components/StatusBadge.vue'
import CategoryBadge from '@/components/CategoryBadge.vue'
import { formatDate } from '@/utils/formatDate'

const projects = ref<ProjectListRow[]>([])
const categories = ref<Category[]>([])
const loading = ref(true)
const error = ref<string | null>(null)

const filterStatus = ref<'' | ProjectStatus>('')
const filterCategory = ref('')
const searchQ = ref('')

async function load() {
  loading.value = true
  error.value = null
  try {
    const [projs, cats] = await Promise.all([
      api.get<Paginated<ProjectListRow>>('/api/projects', { query: { per_page: 100 } }),
      api.get<Wrapped<Category>>('/api/categories'),
    ])
    projects.value = projs.data
    categories.value = cats.data
  } catch (e) {
    error.value = e instanceof ApiError ? (e.payload.message ?? e.code) : 'Erreur réseau'
  } finally {
    loading.value = false
  }
}
onMounted(load)

const filtered = computed(() => {
  let r = projects.value
  if (filterStatus.value) r = r.filter(p => p.status === filterStatus.value)
  if (filterCategory.value) r = r.filter(p => p.category.slug === filterCategory.value)
  if (searchQ.value.trim()) {
    const q = searchQ.value.trim().toLowerCase()
    r = r.filter(p =>
      p.title.toLowerCase().includes(q) ||
      (p.short_description ?? '').toLowerCase().includes(q),
    )
  }
  return r
})

async function destroy(p: ProjectListRow) {
  if (!confirm(`Supprimer le projet « ${p.title} » ?\n(Soft delete, le projet sera retiré des listes publiques.)`)) return
  try {
    await api.delete(`/api/projects/${encodeURIComponent(p.slug)}`)
    projects.value = projects.value.filter(x => x.id !== p.id)
  } catch (e) {
    if (e instanceof ApiError) alert(`Erreur : ${e.payload.message ?? e.code}`)
    else alert('Erreur réseau')
  }
}

async function archive(p: ProjectListRow) {
  if (!confirm(`Archiver le projet « ${p.title} » ?`)) return
  try {
    await api.patch<ProjectListRow>(`/api/projects/${encodeURIComponent(p.slug)}`, { status: 'archived' })
    p.status = 'archived'
  } catch (e) {
    if (e instanceof ApiError) alert(`Erreur : ${e.payload.message ?? e.code}`)
  }
}

async function unarchive(p: ProjectListRow) {
  try {
    await api.patch<ProjectListRow>(`/api/projects/${encodeURIComponent(p.slug)}`, { status: 'active' })
    p.status = 'active'
  } 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">Vue d'ensemble du Donut Infolab — gestion des projets, membres et catégories.</p>
    </header>
    <AdminSubNav />

    <div class="mt-6 flex items-end justify-between gap-4 flex-wrap">
      <div class="flex items-center gap-2 flex-wrap">
        <input
          v-model="searchQ"
          type="search"
          placeholder="Rechercher un projet…"
          class="bg-donut-surface border border-donut-border rounded-lg px-3 py-2 text-sm outline-none focus:border-donut-text w-64"
        />
        <select
          v-model="filterStatus"
          class="bg-donut-surface border border-donut-border rounded-lg px-3 py-2 text-sm outline-none focus:border-donut-text"
        >
          <option value="">Tous statuts</option>
          <option value="active">Actifs</option>
          <option value="completed">Réalisés</option>
          <option value="archived">Archivés</option>
        </select>
        <select
          v-model="filterCategory"
          class="bg-donut-surface border border-donut-border rounded-lg px-3 py-2 text-sm outline-none focus:border-donut-text"
        >
          <option value="">Toutes catégories</option>
          <option v-for="c in categories" :key="c.id" :value="c.slug">{{ c.name }}</option>
        </select>
      </div>
      <RouterLink
        :to="{ name: 'project-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>
        Nouveau projet
      </RouterLink>
    </div>

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

    <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">Titre</th>
            <th class="text-left px-4 py-3 font-medium">Catégorie</th>
            <th class="text-left px-4 py-3 font-medium">Statut</th>
            <th class="text-right px-4 py-3 font-medium tabular-nums">Progression</th>
            <th class="text-left px-4 py-3 font-medium">Créé</th>
            <th class="text-right px-4 py-3 font-medium">Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="filtered.length === 0">
            <td colspan="6" class="px-4 py-8 text-center text-donut-muted text-sm">
              Aucun projet ne correspond aux filtres.
            </td>
          </tr>
          <tr
            v-for="p in filtered" :key="p.id"
            class="border-t border-donut-border hover:bg-gray-50"
          >
            <td class="px-4 py-3">
              <RouterLink
                :to="{ name: 'project-detail', params: { slug: p.slug } }"
                class="font-medium text-donut-text hover:underline"
              >{{ p.title }}</RouterLink>
              <div class="text-xs text-donut-muted truncate max-w-md">{{ p.short_description }}</div>
            </td>
            <td class="px-4 py-3">
              <CategoryBadge :name="p.category.name" :color-hex="p.category.color_hex" />
            </td>
            <td class="px-4 py-3"><StatusBadge :status="p.status" /></td>
            <td class="px-4 py-3 text-right tabular-nums">{{ p.progress_percent }}%</td>
            <td class="px-4 py-3 text-donut-muted">{{ formatDate(p.created_at) }}</td>
            <td class="px-4 py-3 text-right">
              <div class="inline-flex items-center gap-2">
                <RouterLink
                  :to="{ name: 'admin-project-edit', params: { slug: p.slug } }"
                  class="text-donut-text hover:underline text-xs font-medium"
                >Éditer</RouterLink>
                <button
                  v-if="p.status !== 'archived'"
                  type="button"
                  class="text-donut-muted hover:text-donut-text text-xs"
                  @click="archive(p)"
                >Archiver</button>
                <button
                  v-else
                  type="button"
                  class="text-donut-muted hover:text-donut-text text-xs"
                  @click="unarchive(p)"
                >Réactiver</button>
                <button
                  type="button"
                  class="text-red-500 hover:text-red-700 text-xs font-medium"
                  @click="destroy(p)"
                >Supprimer</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <p class="mt-4 text-xs text-donut-muted">{{ filtered.length }} projet{{ filtered.length > 1 ? 's' : '' }} affiché{{ filtered.length > 1 ? 's' : '' }} sur {{ projects.length }} total.</p>
  </section>
</template>
