<template>
  <PageHeader :title="t('nav.groups')">
    <BaseButton variant="ghost" size="sm" :icon="RefreshCw" :loading="groups.loading" @click="refresh">
      {{ t('common.refresh') }}
    </BaseButton>
  </PageHeader>

  <!-- création d'un groupe : nom + sélection des repos déjà enregistrés -->
  <form class="card flex flex-col gap-2" @submit.prevent="onCreate">
    <label class="flex flex-col gap-1 text-xs text-zinc-400">
      {{ t('groups.nameLabel') }}
      <input v-model="newLabel" type="text" class="input" :placeholder="t('groups.namePlaceholder')" required />
    </label>
    <div class="flex flex-col gap-1 text-xs text-zinc-400">
      {{ t('groups.reposLabel') }}
      <p v-if="worktrees.repos.length === 0" class="text-zinc-600">{{ t('groups.noReposRegistered') }}</p>
      <div v-else class="flex flex-wrap gap-2">
        <label
          v-for="repo in worktrees.repos"
          :key="repo.id"
          class="flex items-center gap-1.5 rounded-lg border border-zinc-800 bg-zinc-950/40 px-2 py-1"
        >
          <input v-model="selectedRepoIds" type="checkbox" :value="repo.id" />
          <span class="text-zinc-300">{{ repo.label }}</span>
        </label>
      </div>
    </div>
    <div>
      <BaseButton type="submit" variant="primary" :icon="Plus" :loading="creating" :disabled="newLabel.trim() === ''">
        {{ t('groups.new') }}
      </BaseButton>
    </div>
  </form>

  <SkeletonRow v-if="groups.loading && groups.groups.length === 0" />
  <EmptyState v-else-if="groups.groups.length === 0" :icon="Boxes" :title="t('groups.empty')" />

  <template v-else>
    <ListToolbar :controls="controls" />
    <EmptyState v-if="controls.total.value === 0" :icon="Search" :title="t('controls.results', 0)" />
    <div v-else class="flex flex-col gap-2">
      <article v-for="group in controls.processed.value" :key="group.id" class="card flex items-center gap-3">
      <span class="h-3 w-3 shrink-0 rounded-full" :style="{ backgroundColor: group.color ?? '#52525b' }" />
      <div class="min-w-0 flex-1">
        <RouterLink :to="{ name: 'group', params: { id: group.id } }" class="font-semibold text-zinc-100 hover:underline">
          {{ group.label }}
        </RouterLink>
        <p v-if="group.description" class="truncate text-xs text-zinc-500">{{ group.description }}</p>
      </div>
      <span class="text-xs text-zinc-500">{{ t('groups.repoCount', group.repoIds.length) }}</span>
      <BaseBadge v-if="activeCount(group.id) > 0" tone="emerald">
        {{ t('groups.sessionsActive', activeCount(group.id)) }}
      </BaseBadge>
      <div class="flex items-center gap-2">
        <BaseButton size="sm" :to="{ name: 'group', params: { id: group.id } }">{{ t('groups.open') }}</BaseButton>
        <template v-if="confirmingDelete === group.id">
          <BaseButton variant="danger" size="sm" :icon="Trash2" @click="onDelete(group.id)">{{ t('groups.confirmDelete') }}</BaseButton>
          <BaseButton variant="ghost" size="sm" @click="confirmingDelete = null">{{ t('common.cancel') }}</BaseButton>
        </template>
        <BaseButton v-else variant="danger" size="sm" :icon="Trash2" @click="confirmingDelete = group.id">{{ t('groups.remove') }}</BaseButton>
      </div>
      </article>
    </div>
    <Pagination
      :page="controls.page.value"
      :page-count="controls.pageCount.value"
      :page-size="controls.pageSize.value"
      :page-size-options="[25, 50, 100, 0]"
      :default-size="50"
      @update:page="controls.setPage"
      @update:page-size="controls.setPageSize"
    />
  </template>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import type { GroupSummary } from '@arboretum/shared';
import { RefreshCw, Plus, Trash2, Boxes, Search } from '@lucide/vue';
import { useGroupsStore } from '../stores/groups';
import { useWorktreesStore } from '../stores/worktrees';
import { useToastsStore } from '../stores/toasts';
import { useListControls } from '../composables/useListControls';
import { groupSorts } from '../composables/listDefs';
import PageHeader from '../components/layout/PageHeader.vue';
import BaseButton from '../components/ui/BaseButton.vue';
import BaseBadge from '../components/ui/BaseBadge.vue';
import EmptyState from '../components/ui/EmptyState.vue';
import SkeletonRow from '../components/ui/SkeletonRow.vue';
import ListToolbar from '../components/ListToolbar.vue';
import Pagination from '../components/Pagination.vue';

const { t } = useI18n();
const groups = useGroupsStore();
const worktrees = useWorktreesStore();
const toasts = useToastsStore();

const controls = useListControls<GroupSummary>({
  source: () => groups.groups,
  sorts: groupSorts({ activeCount: (id) => groups.sessionsInGroup(id).filter((s) => s.live).length }),
  searchAccessor: (g) => `${g.label} ${g.description ?? ''}`,
  defaultPageSize: 50,
  urlKey: 'groups',
});

const newLabel = ref('');
const selectedRepoIds = ref<string[]>([]);
const creating = ref(false);
const confirmingDelete = ref<string | null>(null);

// nombre de sessions vivantes corrélées aux repos du groupe (badge d'aperçu).
function activeCount(groupId: string): number {
  return groups.sessionsInGroup(groupId).filter((s) => s.live).length;
}

function refresh(): void {
  void Promise.all([groups.fetchGroups(), worktrees.fetchAll()]);
}

async function onCreate(): Promise<void> {
  creating.value = true;
  try {
    await groups.createGroup({ label: newLabel.value.trim(), repoIds: [...selectedRepoIds.value] });
    newLabel.value = '';
    selectedRepoIds.value = [];
    toasts.success(t('toast.groupCreated'));
  } catch (err) {
    toasts.error(err);
  } finally {
    creating.value = false;
  }
}

async function onDelete(id: string): Promise<void> {
  confirmingDelete.value = null;
  try {
    await groups.deleteGroup(id);
    toasts.success(t('toast.groupDeleted'));
  } catch (err) {
    toasts.error(err);
  }
}
</script>
