<template>
  <AppShell>
    <NSpin :show="store.loading">
      <div class="space-y-6">
        <!-- Header -->
        <div class="flex items-center justify-between">
          <h1 class="text-2xl font-semibold">
            工作区
          </h1>
          <NButton
            type="primary"
            @click="showCreate = true"
          >
            新建工作区
          </NButton>
        </div>

        <!-- Workspace list -->
        <NDataTable
          :columns="columns"
          :data="store.list"
          :loading="store.loading"
          :row-props="rowProps"
          :bordered="false"
          striped
        />

        <div
          v-if="!store.loading && store.list.length === 0"
          class="text-gray-400 text-sm py-8 text-center"
        >
          暂无工作区，点击「新建工作区」创建第一个。
        </div>
      </div>
    </NSpin>

    <!-- Create workspace modal -->
    <WorkspaceCreateModal
      v-if="showCreate"
      :project-slug="projectSlug"
      @close="showCreate = false"
      @created="onCreated"
    />
  </AppShell>
</template>

<script setup lang="ts">
import { h, ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { NButton, NDataTable, NTag, NSpin, useMessage } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import AppShell from '@/layouts/AppShell.vue'
import { useWorkspacesStore } from '@/stores/workspaces'
import type { SyncStatus, Workspace } from '@/api/types'
import WorkspaceCreateModal from './components/WorkspaceCreateModal.vue'

const route = useRoute()
const router = useRouter()
const store = useWorkspacesStore()
const msg = useMessage()

const projectSlug = computed(() => route.params.slug as string)
const showCreate = ref(false)

const SYNC_TAG_TYPE: Record<SyncStatus, 'success' | 'info' | 'warning' | 'error'> = {
  idle: 'success',
  cloning: 'info',
  syncing: 'info',
  error: 'error',
}

const columns: DataTableColumns<Workspace> = [
  { title: '名称', key: 'name' },
  {
    title: 'Slug',
    key: 'slug',
    render: (row) => h('span', { class: 'font-mono text-xs text-gray-500' }, row.slug),
  },
  {
    title: '同步状态',
    key: 'sync_status',
    width: 120,
    render: (row) =>
      h(
        NTag,
        { type: SYNC_TAG_TYPE[row.sync_status] ?? 'default', size: 'small' },
        { default: () => row.sync_status },
      ),
  },
  { title: '默认分支', key: 'default_branch' },
  {
    title: '上次同步',
    key: 'last_synced_at',
    render: (row) => row.last_synced_at ?? '—',
  },
]

function rowProps(row: Workspace) {
  return {
    style: 'cursor: pointer',
    onClick: () => router.push(`/p/${projectSlug.value}/w/${row.slug}`),
  }
}

function onCreated() {
  showCreate.value = false
  store.fetchByProject(projectSlug.value)
}

onMounted(async () => {
  try {
    await store.fetchByProject(projectSlug.value)
  } catch (e: unknown) {
    msg.error('加载工作区失败：' + (e instanceof Error ? e.message : String(e)))
  }
})
</script>
