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

  <form class="card flex flex-col gap-2 sm:flex-row sm:items-end" @submit.prevent="onCreate">
    <label class="flex flex-1 flex-col gap-1 text-xs text-zinc-400">
      {{ t('sessions.cwdLabel') }}
      <input v-model="newCwd" type="text" class="input font-mono" :placeholder="t('sessions.cwdPlaceholder')" required />
    </label>
    <label class="flex flex-col gap-1 text-xs text-zinc-400">
      {{ t('sessions.commandLabel') }}
      <select v-model="newCommand" class="input">
        <option value="claude">claude</option>
        <option value="bash">bash</option>
      </select>
    </label>
    <BaseButton type="button" :icon="FolderOpen" class="whitespace-nowrap" @click="showPicker = !showPicker">
      {{ t('fs.browse') }}
    </BaseButton>
    <BaseButton type="submit" variant="primary" :icon="Plus" class="whitespace-nowrap" :loading="creating" :disabled="newCwd.trim() === ''">
      {{ t('sessions.newSession') }}
    </BaseButton>
  </form>
  <DirectoryPicker
    v-if="showPicker"
    mode="dir"
    :initial-path="newCwd"
    @select="onPickCwd"
    @close="showPicker = false"
  />

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

  <template v-else>
    <ListToolbar :controls="controls" />
    <EmptyState v-if="controls.total.value === 0" :icon="Search" :title="t('controls.results', 0)" />
    <ul v-else class="flex flex-col gap-2">
      <li v-for="s in controls.processed.value" :key="s.id" class="card flex flex-col gap-2">
      <div class="flex items-center gap-2">
        <span class="badge bg-zinc-800 font-mono text-zinc-300">{{ s.command }}</span>
        <BaseBadge v-if="s.source === 'discovered'" tone="sky">{{ t('sessions.sourceDiscovered') }}</BaseBadge>
        <SessionStateBadge :session="s" />
        <span class="ml-auto text-xs text-zinc-500">{{ formatDate(s.createdAt) }}</span>
      </div>
      <p v-if="s.title" class="truncate text-sm text-zinc-200" :title="s.title">{{ s.title }}</p>
      <p class="truncate font-mono text-xs text-zinc-400" :title="s.cwd">{{ s.cwd }}</p>
      <DialogPrompt v-if="s.live && s.activity === 'waiting'" :session="s" />
      <div class="flex flex-wrap items-center gap-2 text-xs text-zinc-500">
        <span v-if="s.live">{{ t('sessions.clients', s.clients) }}</span>
        <span v-if="s.exitCode !== null">· {{ t('sessions.exitCode', { code: s.exitCode }) }}</span>
        <div class="ml-auto flex items-center gap-2">
          <!-- session managée vivante : terminal complet -->
          <template v-if="s.attachable">
            <BaseButton size="sm" :icon="SquareTerminal" :to="{ name: 'session', params: { id: s.id } }">{{ t('sessions.open') }}</BaseButton>
            <BaseButton size="sm" :icon="Eye" :to="{ name: 'session', params: { id: s.id }, query: { mode: 'observer' } }">{{ t('sessions.observe') }}</BaseButton>
            <template v-if="killArmedId === s.id">
              <BaseButton variant="danger" size="sm" :icon="Trash2" :loading="killing" @click="onConfirmKill(s.id)">{{ t('sessions.confirmKill') }}</BaseButton>
              <BaseButton variant="ghost" size="sm" @click="killArmedId = null">{{ t('common.cancel') }}</BaseButton>
            </template>
            <BaseButton v-else variant="danger" size="sm" :icon="Trash2" @click="killArmedId = s.id">{{ t('sessions.kill') }}</BaseButton>
          </template>
          <!-- session externe vivante : pas d'attache (PTY non détenu) → vue read-only ou fork -->
          <template v-else-if="s.live">
            <BaseButton size="sm" :icon="Eye" :to="{ name: 'session', params: { id: s.id } }">{{ t('sessions.view') }}</BaseButton>
            <BaseButton size="sm" :icon="GitFork" :loading="actingId === s.id" @click="onFork(s.id)">{{ t('sessions.fork') }}</BaseButton>
          </template>
          <!-- session morte reprenable : resume direct ou fork -->
          <template v-else-if="s.resumable">
            <BaseButton variant="primary" size="sm" :icon="Play" :loading="actingId === s.id" @click="onResume(s.id)">{{ t('sessions.resume') }}</BaseButton>
            <BaseButton size="sm" :icon="GitFork" :loading="actingId === s.id" @click="onFork(s.id)">{{ t('sessions.fork') }}</BaseButton>
          </template>
        </div>
      </div>
      </li>
    </ul>
    <Pagination
      :page="controls.page.value"
      :page-count="controls.pageCount.value"
      :page-size="controls.pageSize.value"
      @update:page="controls.setPage"
      @update:page-size="controls.setPageSize"
    />
  </template>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import type { SessionSummary } from '@arboretum/shared';
import { RefreshCw, FolderOpen, Plus, TerminalSquare, SquareTerminal, Eye, Trash2, GitFork, Play, Search } from '@lucide/vue';
import { useSessionsStore } from '../stores/sessions';
import { useWorktreesStore } from '../stores/worktrees';
import { useToastsStore } from '../stores/toasts';
import { useListControls } from '../composables/useListControls';
import { sessionSorts, sessionFilters } 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';
import SessionStateBadge from '../components/SessionStateBadge.vue';
import DialogPrompt from '../components/DialogPrompt.vue';
import DirectoryPicker from '../components/DirectoryPicker.vue';

const { t, locale } = useI18n();
const router = useRouter();
const store = useSessionsStore();
const worktrees = useWorktreesStore();
const toasts = useToastsStore();

const controls = useListControls<SessionSummary>({
  source: () => store.sessions,
  sorts: sessionSorts(),
  filters: () => sessionFilters(worktrees.repos),
  searchAccessor: (s) => `${s.cwd} ${s.title ?? ''}`,
  urlKey: 'sessions',
});

const newCwd = ref('');
const newCommand = ref<'claude' | 'bash'>('claude');
const showPicker = ref(false);
const creating = ref(false);
const killArmedId = ref<string | null>(null);
const killing = ref(false);
const actingId = ref<string | null>(null);

onMounted(() => {
  // navigation directe : garantit la liste même si l'AppShell n'a pas encore chargé.
  if (store.sessions.length === 0) void store.fetchSessions();
});

function formatDate(iso: string): string {
  return new Date(iso).toLocaleString(locale.value);
}

function onPickCwd(path: string): void {
  newCwd.value = path;
  showPicker.value = false;
}

async function onCreate(): Promise<void> {
  creating.value = true;
  try {
    const session = await store.createSession(newCwd.value.trim(), newCommand.value);
    newCwd.value = '';
    toasts.success(t('toast.sessionCreated'));
    await router.push({ name: 'session', params: { id: session.id } });
  } catch (err) {
    toasts.error(err);
  } finally {
    creating.value = false;
  }
}

async function onResume(id: string): Promise<void> {
  actingId.value = id;
  try {
    const session = await store.resumeSession(id);
    toasts.success(t('toast.sessionResumed'));
    await router.push({ name: 'session', params: { id: session.id } });
  } catch (err) {
    toasts.error(err);
  } finally {
    actingId.value = null;
  }
}

async function onFork(id: string): Promise<void> {
  actingId.value = id;
  try {
    const session = await store.forkSession(id);
    toasts.success(t('toast.sessionForked'));
    await router.push({ name: 'session', params: { id: session.id } });
  } catch (err) {
    toasts.error(err);
  } finally {
    actingId.value = null;
  }
}

async function onConfirmKill(id: string): Promise<void> {
  killing.value = true;
  try {
    await store.killSession(id);
    toasts.success(t('toast.sessionKilled'));
  } catch {
    // l'état réel arrive par session_exit ; un échec (déjà morte) est sans gravité
  } finally {
    killing.value = false;
    killArmedId.value = null;
  }
}
</script>
