<template>
  <NCard :title="`ACP 开发会话 · ${phaseLabel}`">
    <div class="space-y-3">
      <div class="flex items-center justify-between">
        <span class="text-sm text-gray-500">关联本需求的 agent 会话</span>
        <div class="flex items-center gap-2">
          <NButton size="small" :loading="loading" @click="refresh"> 刷新 </NButton>
          <NTooltip :disabled="!!workspaceSlug">
            <template #trigger>
              <NButton size="small" type="primary" :disabled="!workspaceSlug" @click="goCreate">
                发起{{ phaseLabel }}会话
              </NButton>
            </template>
            需先在左侧「工作区」卡片关联 workspace
          </NTooltip>
        </div>
      </div>

      <NList v-if="sessions.length > 0" :show-divider="false">
        <NListItem v-for="s in sessions" :key="s.id">
          <NThing class="cursor-pointer" @click="goDetail(s)">
            <template #header>
              <span class="font-mono text-sm">{{ s.branch }}</span>
            </template>
            <template #header-extra>
              <SessionStatusBadge :status="s.status" />
            </template>
            <span class="text-xs text-gray-400">
              {{ formatDateTime(s.started_at) }}
              <template v-if="s.last_error"> · {{ s.last_error }}</template>
            </span>
          </NThing>
        </NListItem>
      </NList>
      <NEmpty v-else description="暂无关联会话" size="small" />
    </div>
  </NCard>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { NButton, NCard, NEmpty, NList, NListItem, NThing, NTooltip } from 'naive-ui'

import { acpApi, type AcpSession } from '@/api/acp'
import type { Requirement } from '@/api/projects'
import { formatDateTime } from '@/utils/date'
import SessionStatusBadge from '@/components/acp/SessionStatusBadge.vue'
import { useWorkspacesStore } from '@/stores/workspaces'

const props = defineProps<{
  slug: string
  requirement: Requirement
}>()

const router = useRouter()
const wsStore = useWorkspacesStore()

const sessions = ref<AcpSession[]>([])
const loading = ref(false)

const phaseLabel = computed(() => (props.requirement.phase === 'reviewing' ? '验收' : '实施'))

// requirement.workspace_id → workspace slug（路由需要 wsSlug）。
const workspaceSlug = computed(() => {
  const wsID = props.requirement.workspace_id
  if (!wsID) return null
  return wsStore.list.find((w) => w.id === wsID)?.slug ?? null
})

async function refresh() {
  loading.value = true
  try {
    sessions.value = await acpApi.sessions.list({ requirement_id: props.requirement.id })
  } finally {
    loading.value = false
  }
}

function goCreate() {
  if (!workspaceSlug.value) return
  router.push({
    name: 'acp-sessions-new',
    params: { slug: props.slug, wsSlug: workspaceSlug.value },
    query: { requirement_number: String(props.requirement.number) },
  })
}

function goDetail(s: AcpSession) {
  if (!workspaceSlug.value) return
  router.push({
    name: 'acp-sessions-detail',
    params: { slug: props.slug, wsSlug: workspaceSlug.value, sessionId: s.id },
  })
}

onMounted(refresh)
</script>
