<template>
  <div>
    <div class="flex items-center justify-between mb-6">
      <h1 class="font-display text-2xl font-bold text-white">Messages</h1>
      <span class="text-sm text-white/40">{{ messages?.length || 0 }} message(s)</span>
    </div>

    <div v-if="messages?.length" class="space-y-4">
      <div
        v-for="msg in messages"
        :key="msg.id"
        class="msg-row"
        :class="{ 'msg-row--draft': !msg.published }"
      >
        <!-- En-tête -->
        <div class="flex items-center justify-between gap-4 mb-2">
          <div class="flex items-center gap-2 min-w-0">
            <span class="font-semibold text-white text-sm truncate">{{ msg.author }}</span>
            <span v-if="msg.email" class="text-white/30 text-xs truncate">{{ msg.email }}</span>
            <span class="type-badge" :class="`type-badge--${msg.type || 'reaction'}`">
              {{ typeLabel(msg.type) }}
            </span>
          </div>
          <div class="flex items-center gap-2 shrink-0">
            <span class="text-xs text-white/30">{{ formatDate(msg.createdAt) }}</span>
            <span
              class="status-badge"
              :class="msg.published ? 'status-badge--pub' : 'status-badge--draft'"
            >
              {{ msg.published ? 'Publié' : 'En attente' }}
            </span>
          </div>
        </div>

        <!-- Texte du message -->
        <div v-if="editing === msg.id" class="mb-3 space-y-2">
          <input v-model="editForm.author" class="admin-input w-full" placeholder="Auteur" />
          <select v-model="editForm.type" class="admin-input w-full">
            <option value="question">Question</option>
            <option value="suggestion">Suggestion</option>
            <option value="retour">Retour d'expérience</option>
          </select>
          <textarea v-model="editForm.text" class="admin-input w-full" rows="3" />
        </div>
        <p v-else class="msg-text text-sm leading-relaxed mb-3">{{ msg.text }}</p>

        <!-- Réponse existante -->
        <div v-if="msg.reply && replyEditing !== msg.id" class="reply-block mb-3">
          <div class="flex items-center justify-between mb-1">
            <span class="text-xs font-semibold text-primary/80">Réponse publiée</span>
            <span class="text-xs text-white/30">{{ formatDate(msg.reply.publishedAt) }}</span>
          </div>
          <p class="text-white/60 text-sm leading-relaxed">{{ msg.reply.text }}</p>
          <button class="action-btn mt-2 text-xs" @click="startReply(msg)">
            <div class="i-lucide-pencil h-3 w-3" />
            Modifier la réponse
          </button>
        </div>

        <!-- Formulaire réponse -->
        <div v-if="replyEditing === msg.id" class="reply-form mb-3">
          <textarea
            v-model="replyText"
            class="admin-input w-full text-sm"
            rows="3"
            placeholder="Votre réponse..."
          />
          <div class="flex gap-2 mt-2">
            <button class="action-btn action-btn--save" @click="saveReply(msg)">
              <div class="i-lucide-check h-3.5 w-3.5" />
              Publier la réponse
            </button>
            <button v-if="msg.reply" class="action-btn action-btn--danger" @click="removeReply(msg)">
              <div class="i-lucide-x h-3.5 w-3.5" />
              Supprimer la réponse
            </button>
            <button class="action-btn" @click="replyEditing = null">Annuler</button>
          </div>
        </div>

        <!-- Actions -->
        <div class="flex items-center gap-2 flex-wrap">
          <button class="action-btn" @click="togglePublished(msg)">
            <div :class="msg.published ? 'i-lucide-eye-off' : 'i-lucide-eye'" class="h-3.5 w-3.5" />
            {{ msg.published ? 'Dépublier' : 'Publier' }}
          </button>

          <template v-if="editing === msg.id">
            <button class="action-btn action-btn--save" @click="saveEdit(msg)">
              <div class="i-lucide-check h-3.5 w-3.5" />
              Valider
            </button>
            <button class="action-btn" @click="editing = null">Annuler</button>
          </template>
          <button v-else class="action-btn" @click="startEdit(msg)">
            <div class="i-lucide-pencil h-3.5 w-3.5" />
            Modifier
          </button>

          <button v-if="replyEditing !== msg.id && !msg.reply" class="action-btn action-btn--reply" @click="startReply(msg)">
            <div class="i-lucide-reply h-3.5 w-3.5" />
            Répondre
          </button>

          <button class="action-btn action-btn--danger ml-auto" @click="remove(msg)">
            <div class="i-lucide-trash-2 h-3.5 w-3.5" />
            Supprimer
          </button>
        </div>
      </div>
    </div>

    <p v-else class="text-center text-white/40 py-12">Aucun message.</p>
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  layout: 'admin',
  middleware: 'admin',
})

const { data: messages, refresh } = await useFetch<any[]>('/api/admin/messages')

const editing = ref<number | null>(null)
const editForm = reactive({ author: '', text: '', type: 'question' })

const replyEditing = ref<number | null>(null)
const replyText = ref('')

const TYPE_LABELS: Record<string, string> = {
  reaction: 'Réaction',
  question: 'Question',
  suggestion: 'Suggestion',
  retour: 'Retour',
}

function typeLabel(type: string) {
  return TYPE_LABELS[type] ?? type
}

function startEdit(msg: any) {
  editing.value = msg.id
  editForm.author = msg.author
  editForm.text = msg.text
  editForm.type = TYPE_LABELS[msg.type] ? msg.type : 'question'
}

async function saveEdit(msg: any) {
  await $fetch(`/api/admin/messages/${msg.id}`, {
    method: 'PUT',
    body: { author: editForm.author, text: editForm.text, type: editForm.type },
  })
  editing.value = null
  await refresh()
}

async function togglePublished(msg: any) {
  await $fetch(`/api/admin/messages/${msg.id}`, {
    method: 'PUT',
    body: { published: !msg.published },
  })
  await refresh()
}

function startReply(msg: any) {
  replyEditing.value = msg.id
  replyText.value = msg.reply?.text ?? ''
}

async function saveReply(msg: any) {
  await $fetch(`/api/admin/messages/${msg.id}`, {
    method: 'PUT',
    body: { reply: replyText.value.trim() || null },
  })
  replyEditing.value = null
  await refresh()
}

async function removeReply(msg: any) {
  await $fetch(`/api/admin/messages/${msg.id}`, {
    method: 'PUT',
    body: { reply: null },
  })
  replyEditing.value = null
  await refresh()
}

async function remove(msg: any) {
  if (!confirm(`Supprimer le message de "${msg.author}" ?`)) return
  await $fetch(`/api/admin/messages/${msg.id}`, { method: 'DELETE' })
  await refresh()
}

function formatDate(iso: string) {
  return new Date(iso).toLocaleDateString('fr-FR', {
    day: 'numeric',
    month: 'short',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}
</script>

<style scoped>
.msg-row {
  background: hsl(var(--color-bg));
  border: 1px solid hsl(var(--color-surface-light));
  border-radius: 0.75rem;
  padding: 1rem 1.25rem;
}

.msg-row--draft {
  border-left: 3px solid hsl(var(--color-accent));
}

.status-badge {
  font-size: 0.65rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  padding: 0.15rem 0.5rem;
  border-radius: 9999px;
}

.status-badge--pub {
  background: hsl(142 70% 40% / 0.15);
  color: hsl(142 70% 60%);
}

.status-badge--draft {
  background: hsl(var(--color-accent) / 0.15);
  color: hsl(var(--color-accent));
}

.type-badge {
  font-size: 0.6rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  padding: 0.1rem 0.45rem;
  border-radius: 9999px;
  background: hsl(var(--color-primary) / 0.12);
  color: hsl(var(--color-primary) / 0.7);
}

.type-badge--question {
  background: hsl(220 70% 50% / 0.12);
  color: hsl(220 70% 65%);
}

.type-badge--suggestion {
  background: hsl(280 60% 55% / 0.12);
  color: hsl(280 60% 70%);
}

.type-badge--retour {
  background: hsl(35 70% 50% / 0.12);
  color: hsl(35 70% 65%);
}

.reply-block {
  background: hsl(var(--color-primary) / 0.06);
  border-left: 2px solid hsl(var(--color-primary) / 0.3);
  border-radius: 0 0.5rem 0.5rem 0;
  padding: 0.75rem 1rem;
}

.reply-form {
  background: hsl(var(--color-surface) / 0.5);
  border-radius: 0.5rem;
  padding: 0.75rem;
}

.admin-input {
  padding: 0.375rem 0.5rem;
  border-radius: 0.375rem;
  border: 1px solid hsl(var(--color-surface-light));
  background: hsl(var(--color-bg));
  color: hsl(var(--color-text));
  font-size: 0.8rem;
}

.admin-input:focus {
  outline: none;
  border-color: hsl(var(--color-primary) / 0.5);
}

.action-btn {
  display: inline-flex;
  align-items: center;
  gap: 0.35rem;
  padding: 0.3rem 0.6rem;
  border-radius: 0.375rem;
  font-size: 0.75rem;
  color: hsl(var(--color-text-muted));
  background: none;
  border: 1px solid hsl(var(--color-surface-light));
  cursor: pointer;
  transition: all 0.2s;
}

.action-btn:hover {
  background: hsl(var(--color-surface));
  color: hsl(var(--color-text));
}

.action-btn--save {
  border-color: hsl(142 70% 40% / 0.3);
  color: hsl(142 70% 60%);
}

.action-btn--save:hover {
  background: hsl(142 70% 40% / 0.1);
}

.action-btn--reply {
  border-color: hsl(var(--color-primary) / 0.3);
  color: hsl(var(--color-primary) / 0.8);
}

.action-btn--reply:hover {
  background: hsl(var(--color-primary) / 0.08);
}

.msg-text {
  color: hsl(var(--color-text) / 0.72);
  white-space: pre-line;
}

.action-btn--danger:hover {
  background: hsl(0 70% 40% / 0.1);
  border-color: hsl(0 70% 40% / 0.3);
  color: hsl(0 70% 60%);
}
</style>
