<script setup lang="ts">
import { onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { NButton, NSpin } from 'naive-ui'
import AppShell from '@/layouts/AppShell.vue'
import { useAcpStore } from '@/stores/acp'
import { useConfirm } from '@/composables/useConfirm'
import { useAlert } from '@/composables/useAlert'

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

onMounted(() => store.listAgentKinds(true))

async function toggleEnabled(id: string, enabled: boolean) {
  await store.updateAgentKind(id, { enabled })
}

function goNew() {
  router.push('/admin/acp/agent-kinds/new')
}

function goEdit(id: string) {
  router.push(`/admin/acp/agent-kinds/${id}`)
}

async function remove(id: string, name: string) {
  const ok = await confirm(`Delete agent kind "${name}"?`)
  if (!ok) return
  try {
    await store.deleteAgentKind(id)
  } catch (e) {
    alert(`Delete failed: ${e instanceof Error ? e.message : 'unknown'}`)
  }
}
</script>

<template>
  <AppShell>
    <NSpin :show="store.loading">
      <div class="space-y-4">
        <div class="flex items-center justify-between">
          <h1 class="text-2xl font-semibold">ACP Agent Kinds</h1>
          <NButton type="primary" @click="goNew"> + New </NButton>
        </div>
        <div v-if="store.error" class="text-red-600">
          {{ store.error }}
        </div>
        <table v-else class="w-full text-sm">
          <thead class="text-left">
            <tr>
              <th class="px-3 py-2">Name</th>
              <th class="px-3 py-2">Display</th>
              <th class="px-3 py-2">Binary</th>
              <th class="px-3 py-2">Enabled</th>
              <th class="px-3 py-2 text-right">Actions</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="k in store.agentKinds" :key="k.id" class="border-t">
              <td class="px-3 py-2 font-mono">
                {{ k.name }}
              </td>
              <td class="px-3 py-2">
                {{ k.display_name }}
              </td>
              <td class="px-3 py-2 font-mono text-xs">
                {{ k.binary_path }}
              </td>
              <td class="px-3 py-2">
                <input
                  type="checkbox"
                  :checked="k.enabled"
                  @change="toggleEnabled(k.id, !k.enabled)"
                />
              </td>
              <td class="px-3 py-2 text-right space-x-2">
                <NButton text type="primary" @click="goEdit(k.id)"> Edit </NButton>
                <NButton text type="error" @click="remove(k.id, k.name)"> Delete </NButton>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </NSpin>
  </AppShell>
</template>
