<script setup lang="ts">
import { onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { NButton } from 'naive-ui'
import { useAcpStore } from '@/stores/acp'
import { useConfirm } from '@/composables/useConfirm'
import { useAlert } from '@/composables/useAlert'
import { formatDateTime } from '@/utils/date'
import SessionStatusBadge from '@/components/acp/SessionStatusBadge.vue'

const route = useRoute()
const router = useRouter()
const store = useAcpStore()
const confirm = useConfirm()
const alert = useAlert()

onMounted(() => {
  void store.listSessions(false)
})

function open(id: string) {
  router.push(`/p/${route.params.slug}/w/${route.params.wsSlug}/acp-sessions/${id}`)
}

function newSession() {
  router.push(`/p/${route.params.slug}/w/${route.params.wsSlug}/acp-sessions/new`)
}

async function terminate(id: string) {
  const ok = await confirm('Terminate this session?')
  if (!ok) return
  try {
    await store.terminateSession(id)
  } catch (e) {
    alert(e instanceof Error ? e.message : 'failed')
  }
}
</script>

<template>
  <div class="p-6 space-y-4">
    <div class="flex items-center justify-between">
      <h1 class="text-2xl font-semibold">ACP Sessions</h1>
      <NButton type="primary" @click="newSession"> + New </NButton>
    </div>

    <div v-if="store.loading" class="text-gray-500">Loading...</div>
    <div v-else-if="store.error" class="text-red-600">
      {{ store.error }}
    </div>
    <div v-else-if="store.sessions.length === 0" class="text-gray-500">
      No sessions yet. Click "+ New" to create one.
    </div>

    <table v-else class="w-full text-sm">
      <thead class="text-left">
        <tr class="border-b">
          <th class="px-3 py-2">Branch</th>
          <th class="px-3 py-2">Status</th>
          <th class="px-3 py-2">Started</th>
          <th class="px-3 py-2 text-right">Actions</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="s in store.sessions" :key="s.id" class="border-t hover:bg-gray-50">
          <td class="px-3 py-2 font-mono text-xs">
            {{ s.branch }}
          </td>
          <td class="px-3 py-2">
            <SessionStatusBadge :status="s.status" />
          </td>
          <td class="px-3 py-2 text-xs text-gray-500">
            {{ formatDateTime(s.started_at) }}
          </td>
          <td class="px-3 py-2 text-right space-x-2">
            <NButton text type="primary" @click="open(s.id)"> Open </NButton>
            <NButton
              v-if="s.status === 'starting' || s.status === 'running'"
              text
              type="error"
              @click="terminate(s.id)"
            >
              Terminate
            </NButton>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>
