<template>
  <div class="card-surface !p-0">
    <div class="flex items-center justify-center py-3 px-4">
      <p class="gw-metric text-sm">Mes relations</p>
    </div>
    <div class="overflow-x-auto">
      <table class="w-full text-sm">
        <thead>
          <tr class="border-b border-white/8">
            <th
              v-for="col in columns"
              :key="col.key"
              class="px-3 py-2 text-left text-xs font-semibold text-white/60 uppercase cursor-pointer select-none hover:text-white/80 transition-colors"
              @click="col.sortable && toggleSort(col.key)"
            >
              <span class="inline-flex items-center gap-1">
                {{ col.label }}
                <span v-if="col.sortable && sortKey === col.key" class="text-accent">
                  {{ sortAsc ? '\u25B2' : '\u25BC' }}
                </span>
              </span>
            </th>
            <th class="px-3 py-2 w-8" />
          </tr>
        </thead>
        <tbody>
          <tr v-if="sortedItems.length === 0">
            <td :colspan="columns.length + 1" class="px-3 py-3 text-center text-white/40 text-xs">
              Aucune relation
            </td>
          </tr>
          <tr
            v-for="(friend, index) in sortedItems"
            :key="friend.name"
            class="cursor-pointer border-b border-white/5 transition-colors"
            :class="index % 2 === 0 ? 'bg-surface-200/50' : ''"
            @click="emit('select', friend)"
          >
            <td class="px-3 py-1.5">{{ friend.displayName }}</td>
            <td v-if="resultLabel" class="px-3 py-1.5">{{ friend.result }}</td>
            <td class="px-3 py-1.5">{{ friend.displayDate }}</td>
            <td class="px-3 py-1.5">{{ friend.du }}</td>
            <td class="px-3 py-1.5 w-8">
              <button
                v-if="!isBaseFriend(friend)"
                class="text-red-400 hover:text-red-300 transition-colors"
                title="Effacer relation"
                @click.stop="emit('remove', friend.name)"
              >
                <svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <circle cx="12" cy="12" r="10" />
                  <path d="M15 9l-6 6M9 9l6 6" />
                </svg>
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Block0Date, type TableFriend } from '~/utils/gratewizard';

const props = defineProps<{
  items: TableFriend[];
  baseFriends: { name: string; date: string }[];
  resultLabel?: string;
}>();

const emit = defineEmits<{
  select: [friend: TableFriend];
  remove: [name: string];
}>();

const sortKey = ref<string>('name');
const sortAsc = ref(true);

const columns = computed(() => {
  const cols = [
    { key: 'name', label: 'NOM', sortable: true },
  ];
  if (props.resultLabel) {
    cols.push({ key: 'result', label: props.resultLabel, sortable: true });
  }
  cols.push(
    { key: 'date', label: 'DATE', sortable: true },
    { key: 'du', label: 'DU', sortable: true },
  );
  return cols;
});

function toggleSort(key: string) {
  if (sortKey.value === key) {
    sortAsc.value = !sortAsc.value;
  } else {
    sortKey.value = key;
    sortAsc.value = true;
  }
}

const sortedItems = computed(() => {
  const baseNames = new Set(props.baseFriends.map((f) => f.name));
  const bases: TableFriend[] = [];
  const others: TableFriend[] = [];

  for (const item of props.items) {
    if (baseNames.has(item.name)) bases.push(item);
    else others.push(item);
  }

  const key = sortKey.value;
  const dir = sortAsc.value ? 1 : -1;

  others.sort((a, b) => {
    const first = a[key];
    const second = b[key];
    let cmp = 0;
    switch (key) {
      case 'name':
        cmp = String(first).localeCompare(String(second));
        break;
      case 'result':
      case 'du':
        cmp = Number(first) - Number(second);
        break;
      case 'date':
        cmp = new Date(a.date).getTime() - new Date(b.date).getTime();
        break;
    }
    return cmp * dir;
  });

  return [...bases, ...others];
});

function isBaseFriend(friend: TableFriend): boolean {
  return props.baseFriends.some(({ name, date }) => name === friend.name && date === friend.date);
}
</script>
