<template>
  <section class="space-y-4" aria-live="polite">
    <header class="flex flex-col gap-1 sm:flex-row sm:items-end sm:justify-between">
      <div>
        <h2 class="text-xl font-semibold text-base-content">Catégories enregistrées</h2>
        <p class="text-sm text-base-content/70">
          {{ totalLabel }}
        </p>
      </div>
      <p v-if="loading" class="text-sm text-info flex items-center gap-2">
        <span class="loading loading-spinner loading-xs" aria-hidden="true"></span>
        Chargement en cours…
      </p>
    </header>

    <div v-if="loading && items.length === 0" class="space-y-3" role="status" aria-live="polite">
      <div
        v-for="index in 3"
        :key="index"
        class="rounded-xl border border-base-200 bg-base-200/70 animate-pulse h-24"
      ></div>
    </div>

    <div v-else-if="items.length === 0" class="rounded-xl border border-dashed border-base-200 p-10 text-center">
      <IconLucideInbox class="mx-auto h-12 w-12 text-base-content/30" aria-hidden="true" />
      <h3 class="mt-4 text-lg font-medium text-base-content">Aucune catégorie trouvée</h3>
      <p class="text-sm text-base-content/70">Ajustez votre recherche ou créez une nouvelle catégorie.</p>
    </div>

    <div v-else class="space-y-6">
      <div class="hidden sm:block overflow-x-auto">
        <table class="table">
          <thead>
            <tr class="text-base-content/70">
              <th scope="col">Nom</th>
              <th scope="col">Notes</th>
              <th scope="col" class="w-48 text-right">Actions</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in items" :key="item.id">
              <td class="font-medium">{{ item.name }}</td>
              <td class="max-w-xs align-middle">
                <span v-if="item.notes" class="block text-sm text-base-content/80 break-words">{{ item.notes }}</span>
                <span v-else class="text-base-content/50">—</span>
              </td>
              <td class="text-right space-x-2">
                <button type="button" class="btn btn-ghost btn-sm" @click="emit('related', item)">
                  Liés
                </button>
                <button
                  v-if="canEdit && showConvertButton"
                  type="button"
                  class="btn btn-ghost btn-sm text-warning"
                  @click="emit('convert', item)"
                >
                  <IconLucideArrowLeftRight class="h-4 w-4" aria-hidden="true" />
                  Convertir
                </button>
                <button type="button" class="btn btn-ghost btn-sm" @click="emit('edit', item)">
                  Éditer
                </button>
                <button v-if="canEdit" type="button" class="btn btn-ghost btn-sm text-error" @click="emit('delete', item)">
                  Supprimer
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="grid gap-4 sm:hidden">
        <article
          v-for="item in items"
          :key="item.id"
          class="rounded-xl border border-base-200 bg-base-100 p-4 shadow-sm"
        >
          <header class="flex items-start justify-between gap-3">
            <div>
              <h3 class="text-lg font-semibold text-base-content">{{ item.name }}</h3>
              <p class="text-sm text-base-content/60">{{ categoryLabel(item.category) }}</p>
            </div>
          </header>
          <p class="mt-3 text-sm text-base-content/80" v-if="item.notes">{{ item.notes }}</p>
          <p class="mt-3 text-sm text-base-content/50" v-else>Pas de notes</p>
          <footer class="mt-4 flex flex-wrap items-center gap-2 justify-end">
            <button type="button" class="btn btn-ghost btn-sm" @click="emit('related', item)">
              Liés
            </button>
            <button
              v-if="canEdit && showConvertButton"
              type="button"
              class="btn btn-ghost btn-sm text-warning"
              @click="emit('convert', item)"
            >
              <IconLucideArrowLeftRight class="h-4 w-4" aria-hidden="true" />
              Convertir
            </button>
            <button type="button" class="btn btn-ghost btn-sm" @click="emit('edit', item)">
              Éditer
            </button>
            <button v-if="canEdit" type="button" class="btn btn-ghost btn-sm text-error" @click="emit('delete', item)">
              Supprimer
            </button>
          </footer>
        </article>
      </div>

      <nav class="flex flex-wrap items-center justify-between gap-3" aria-label="Pagination">
        <span class="text-sm text-base-content/70">
          Page {{ currentPage }} sur {{ totalPages }}
        </span>
        <div class="join">
          <button
            type="button"
            class="btn btn-outline btn-sm join-item"
            :disabled="!canGoPrevious"
            @click="emit('update:offset', Math.max(0, offset - limit))"
          >
            Précédent
          </button>
          <button
            type="button"
            class="btn btn-outline btn-sm join-item"
            :disabled="!canGoNext"
            @click="emit('update:offset', offset + limit)"
          >
            Suivant
          </button>
        </div>
      </nav>
    </div>
  </section>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import IconLucideInbox from '~icons/lucide/inbox';
import IconLucideArrowLeftRight from '~icons/lucide/arrow-left-right';
import type { ModelType, ModelCategory } from '~/services/modelTypes';

const props = defineProps<{
  items: ModelType[];
  loading: boolean;
  total: number;
  limit: number;
  offset: number;
  category?: ModelCategory;
  canEdit?: boolean;
}>();

const emit = defineEmits<{
  (e: 'related', item: ModelType): void;
  (e: 'edit', item: ModelType): void;
  (e: 'delete', item: ModelType): void;
  (e: 'convert', item: ModelType): void;
  (e: 'update:offset', offset: number): void;
}>();

const showConvertButton = computed(() =>
  props.category === 'PIECE' || props.category === 'COMPONENT',
);

const categoryDictionary: Record<ModelCategory, string> = {
  COMPONENT: 'Composants',
  PIECE: 'Pièces',
  PRODUCT: 'Produits',
};

const categoryLabel = (category: ModelCategory) => categoryDictionary[category] ?? category;

const currentPage = computed(() => {
  if (props.limit <= 0) return 1;
  return Math.floor(props.offset / props.limit) + 1;
});

const totalPages = computed(() => {
  if (props.limit <= 0) return 1;
  return Math.max(1, Math.ceil(props.total / props.limit));
});

const canGoPrevious = computed(() => props.offset > 0);
const canGoNext = computed(() => props.offset + props.limit < props.total);

const totalLabel = computed(() => {
  if (props.total === 0) return 'Aucun résultat';
  if (props.total === 1) return '1 catégorie trouvée';
  return `${props.total} catégories trouvées`;
});
</script>
