<template>
  <AppShell>
    <div class="space-y-4">
      <NPageHeader :title="store.current?.name ?? wsSlug">
        <template #subtitle>
          {{ store.current?.slug }}
        </template>
      </NPageHeader>

      <SyncBar
        v-if="store.current"
        :ws="store.current"
      />

      <NTabs
        v-model:value="tab"
        type="line"
      >
        <NTabPane
          name="worktrees"
          tab="Worktrees"
        >
          <WorktreesTab
            v-if="store.current"
            :ws="store.current"
          />
        </NTabPane>
        <NTabPane
          name="main"
          tab="Main"
        >
          <MainTab
            v-if="store.current"
            :ws="store.current"
          />
        </NTabPane>
        <NTabPane
          name="commits"
          tab="Commits"
        >
          <CommitHistoryTab
            v-if="store.current"
            :ws="store.current"
          />
        </NTabPane>
        <NTabPane
          name="runs"
          tab="Run"
        >
          <RunsTab
            v-if="store.current"
            :ws="store.current"
          />
        </NTabPane>
        <NTabPane
          name="settings"
          tab="Settings"
        >
          <SettingsTab
            v-if="store.current"
            :ws="store.current"
          />
        </NTabPane>
      </NTabs>
    </div>
  </AppShell>
</template>

<script setup lang="ts">
import { onMounted, ref, computed, defineAsyncComponent } from 'vue'
import { useRoute } from 'vue-router'
import { NTabs, NTabPane, NPageHeader, useMessage } from 'naive-ui'
import AppShell from '@/layouts/AppShell.vue'
import { useWorkspacesStore } from '@/stores/workspaces'
import SyncBar from './components/SyncBar.vue'
const WorktreesTab = defineAsyncComponent(() => import('./components/WorktreesTab.vue'))
const MainTab = defineAsyncComponent(() => import('./components/MainTab.vue'))
const CommitHistoryTab = defineAsyncComponent(() => import('./components/CommitHistoryTab.vue'))
const SettingsTab = defineAsyncComponent(() => import('./components/SettingsTab.vue'))
const RunsTab = defineAsyncComponent(() => import('./components/RunsTab.vue'))

const route = useRoute()
const store = useWorkspacesStore()
const msg = useMessage()
const tab = ref<'worktrees' | 'main' | 'commits' | 'settings' | 'runs'>('worktrees')

const projectSlug = computed(() => route.params.slug as string)
const wsSlug = computed(() => route.params.wsSlug as string)

onMounted(async () => {
  try {
    // 通过 fetchByProject 拿列表后定位 wsID
    await store.fetchByProject(projectSlug.value)
    const ws = store.list.find((w) => w.slug === wsSlug.value)
    if (!ws) {
      msg.error('找不到工作区')
      return
    }
    await store.fetchOne(ws.id)
    await store.fetchWorktrees(ws.id)
    await store.fetchCredential(ws.id)
  } catch (e: unknown) {
    msg.error('加载失败：' + (e instanceof Error ? e.message : String(e)))
  }
})
</script>
