<template>
  <section class="space-y-3 rounded-lg border border-base-200 bg-base-200/40 p-4">
    <header class="flex items-center justify-between gap-3">
      <div>
        <h2 class="font-semibold text-base-content">Historique</h2>
        <p class="text-xs text-base-content/70">
          Qui a changé quoi, et quand.
        </p>
      </div>
      <span v-if="entries.length" class="badge badge-outline">
        {{ entries.length }} entrée{{ entries.length > 1 ? 's' : '' }}
      </span>
    </header>

    <div v-if="loading" class="flex items-center gap-2 text-sm text-base-content/70">
      <span class="loading loading-spinner loading-sm" aria-hidden="true" />
      Chargement de l'historique…
    </div>

    <div v-else-if="error" class="alert alert-warning">
      <span>{{ error }}</span>
    </div>

    <p v-else-if="entries.length === 0" class="text-xs text-base-content/70">
      Aucun changement enregistré pour le moment.
    </p>

    <ul v-else class="max-h-80 space-y-2 overflow-y-auto pr-1">
      <li
        v-for="entry in entries"
        :key="entry.id"
        class="rounded-md border border-base-200 bg-base-100 px-3 py-2"
      >
        <div class="flex flex-wrap items-center justify-between gap-2 text-xs text-base-content/70">
          <span class="font-medium text-base-content">
            {{ historyActionLabel(entry.action) }}
          </span>
          <span>{{ formatHistoryDate(entry.createdAt) }}</span>
        </div>
        <p class="mt-1 text-xs text-base-content/60">
          Par {{ entry.actor?.label || 'Inconnu' }}
        </p>

        <ul
          v-if="diffEntries(entry).length"
          class="mt-2 space-y-1 text-xs"
        >
          <li
            v-for="diffEntry in diffEntries(entry)"
            :key="`${entry.id}-${diffEntry.field}`"
            class="flex flex-col gap-0.5"
          >
            <span class="font-medium text-base-content/80">{{ diffEntry.label }}</span>
            <span class="text-base-content/60">
              {{ diffEntry.fromLabel }} → {{ diffEntry.toLabel }}
            </span>
          </li>
        </ul>

        <p
          v-else-if="entry.snapshot?.name"
          class="mt-2 text-xs text-base-content/70"
        >
          {{ entry.snapshot.name }}
        </p>
      </li>
    </ul>
  </section>
</template>

<script setup lang="ts">
import {
  historyActionLabel,
  formatHistoryDate,
  historyDiffEntries,
  type HistoryDiffEntry,
} from '~/shared/utils/historyDisplayUtils'

interface HistoryEntry {
  id: string
  action: string
  createdAt: string
  actor?: { label?: string } | null
  diff?: Record<string, { from?: unknown; to?: unknown }> | null
  snapshot?: { name?: string } | null
}

const props = defineProps<{
  entries: HistoryEntry[]
  loading?: boolean
  error?: string | null
  fieldLabels: Record<string, string>
}>()

const diffEntries = (entry: HistoryEntry): HistoryDiffEntry[] =>
  historyDiffEntries(entry, props.fieldLabels)
</script>
