<template>
  <div class="overflow-y-auto">
    <div class="mx-auto flex max-w-3xl flex-col gap-4 px-4 py-6">
      <header class="flex items-center gap-3">
        <h1 class="text-lg font-semibold text-zinc-100">{{ t('sessions.title') }}</h1>
        <span v-if="auth.serverVersion" class="text-xs text-zinc-600">v{{ auth.serverVersion }}</span>
        <div class="ml-auto flex items-center gap-2">
          <RouterLink :to="{ name: 'dashboard' }" class="btn">{{ t('dashboard.title') }}</RouterLink>
          <button class="btn" :disabled="store.loading" @click="store.fetchSessions()">
            {{ t('sessions.refresh') }}
          </button>
          <LanguageSwitcher />
          <button class="btn" @click="onLogout">{{ t('common.logout') }}</button>
        </div>
      </header>

      <form
        class="flex flex-col gap-2 rounded-lg border border-zinc-800 bg-zinc-900/50 p-3 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>
        <button type="submit" class="btn-primary whitespace-nowrap" :disabled="creating || newCwd.trim() === ''">
          {{ creating ? t('sessions.creating') : t('sessions.newSession') }}
        </button>
      </form>
      <p v-if="createError" class="text-sm text-red-400">{{ createError }}</p>
      <p v-if="actionError" class="text-sm text-red-400">{{ actionError }}</p>

      <p v-if="store.loadError" class="text-sm text-red-400">{{ store.loadError }}</p>
      <p v-else-if="store.loading && store.sessions.length === 0" class="text-sm text-zinc-500">
        {{ t('common.loading') }}
      </p>
      <p v-else-if="store.sessions.length === 0" class="text-sm text-zinc-500">{{ t('sessions.empty') }}</p>

      <ul class="flex flex-col gap-2">
        <li
          v-for="s in store.sessions"
          :key="s.id"
          class="flex flex-col gap-2 rounded-lg border border-zinc-800 bg-zinc-900/50 p-3"
        >
          <div class="flex items-center gap-2">
            <span class="badge bg-zinc-800 font-mono text-zinc-300">{{ s.command }}</span>
            <span v-if="s.source === 'discovered'" class="badge bg-sky-950 text-sky-400">
              {{ t('sessions.sourceDiscovered') }}
            </span>
            <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>
          <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">
                <RouterLink :to="{ name: 'session', params: { id: s.id } }" class="btn">{{ t('sessions.open') }}</RouterLink>
                <RouterLink :to="{ name: 'session', params: { id: s.id }, query: { mode: 'observer' } }" class="btn">
                  {{ t('sessions.observe') }}
                </RouterLink>
                <template v-if="killArmedId === s.id">
                  <button class="btn-danger" :disabled="killing" @click="onConfirmKill(s.id)">
                    {{ t('sessions.confirmKill') }}
                  </button>
                  <button class="btn" @click="killArmedId = null">{{ t('common.cancel') }}</button>
                </template>
                <button v-else class="btn-danger" @click="killArmedId = s.id">{{ t('sessions.kill') }}</button>
              </template>
              <!-- session externe vivante : pas d'attache (PTY non détenu) → vue read-only ou fork -->
              <template v-else-if="s.live">
                <RouterLink :to="{ name: 'session', params: { id: s.id } }" class="btn">{{ t('sessions.view') }}</RouterLink>
                <button class="btn" :disabled="actingId === s.id" @click="onFork(s.id)">{{ t('sessions.fork') }}</button>
              </template>
              <!-- session morte reprenable : resume direct ou fork -->
              <template v-else-if="s.resumable">
                <button class="btn-primary" :disabled="actingId === s.id" @click="onResume(s.id)">
                  {{ t('sessions.resume') }}
                </button>
                <button class="btn" :disabled="actingId === s.id" @click="onFork(s.id)">{{ t('sessions.fork') }}</button>
              </template>
            </div>
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useAuthStore } from '../stores/auth';
import { useSessionsStore } from '../stores/sessions';
import LanguageSwitcher from '../components/LanguageSwitcher.vue';
import SessionStateBadge from '../components/SessionStateBadge.vue';

const { t, locale } = useI18n();
const router = useRouter();
const auth = useAuthStore();
const store = useSessionsStore();

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

onMounted(() => {
  void store.fetchSessions();
  store.startRealtime();
});

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

async function onCreate(): Promise<void> {
  creating.value = true;
  createError.value = null;
  try {
    const session = await store.createSession(newCwd.value.trim(), newCommand.value);
    newCwd.value = '';
    await router.push({ name: 'session', params: { id: session.id } });
  } catch (err) {
    createError.value = err instanceof Error ? err.message : String(err);
  } finally {
    creating.value = false;
  }
}

async function onResume(id: string): Promise<void> {
  actingId.value = id;
  actionError.value = null;
  try {
    const session = await store.resumeSession(id);
    await router.push({ name: 'session', params: { id: session.id } });
  } catch (err) {
    actionError.value = err instanceof Error ? err.message : String(err);
  } finally {
    actingId.value = null;
  }
}

async function onFork(id: string): Promise<void> {
  actingId.value = id;
  actionError.value = null;
  try {
    const session = await store.forkSession(id);
    await router.push({ name: 'session', params: { id: session.id } });
  } catch (err) {
    actionError.value = err instanceof Error ? err.message : String(err);
  } finally {
    actingId.value = null;
  }
}

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

async function onLogout(): Promise<void> {
  store.stopRealtime();
  await auth.logout();
  await router.replace({ name: 'login' });
}
</script>
