<template>
  <div class="space-y-4">
    <!-- 目标选择：main 或某个 worktree -->
    <div class="flex items-center gap-3">
      <span class="text-sm text-gray-500">查看目标</span>
      <NSelect v-model:value="target" :options="targetOptions" size="small" class="w-64" />
      <NButton size="small" :loading="loading" @click="refresh"> 刷新 </NButton>
    </div>

    <NDataTable
      :columns="columns"
      :data="commits"
      :loading="loading"
      size="small"
      :scroll-x="800"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, h, onMounted, ref, watch } from 'vue'
import { NButton, NDataTable, NSelect, NTag, NTooltip } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'

import { workspacesApi } from '@/api/workspaces'
import { useWorkspacesStore } from '@/stores/workspaces'
import { formatDateTime } from '@/utils/date'
import type { CommitLog, Workspace } from '@/api/types'

const props = defineProps<{ ws: Workspace }>()
const store = useWorkspacesStore()

const target = ref<string>('main')
const commits = ref<CommitLog[]>([])
const loading = ref(false)

const targetOptions = computed(() => {
  const opts = [{ label: `Main (${props.ws.default_branch})`, value: 'main' }]
  for (const wt of store.worktrees) {
    opts.push({ label: wt.branch, value: wt.id })
  }
  return opts
})

function shortHash(hash: string) {
  return hash.slice(0, 8)
}

const columns = computed<DataTableColumns<CommitLog>>(() => [
  {
    title: 'Commit',
    key: 'hash',
    width: 100,
    fixed: 'left',
    render(row: CommitLog) {
      return h(NTag, { size: 'tiny', type: 'default' }, { default: () => shortHash(row.hash) })
    },
  },
  {
    title: '提交信息',
    key: 'subject',
    ellipsis: { tooltip: true },
  },
  {
    title: '作者',
    key: 'author',
    width: 140,
    render(row: CommitLog) {
      return h(
        NTooltip,
        {},
        {
          trigger: () => h('span', row.author),
          default: () => row.email,
        },
      )
    },
  },
  {
    title: '时间',
    key: 'date',
    width: 160,
    render(row: CommitLog) {
      return h('span', { class: 'text-xs text-gray-500' }, formatDateTime(row.date))
    },
  },
])

async function refresh() {
  loading.value = true
  try {
    if (target.value === 'main') {
      commits.value = await workspacesApi.logOnMain(props.ws.id)
    } else {
      commits.value = await workspacesApi.logOnWorktree(target.value)
    }
  } catch {
    commits.value = []
  } finally {
    loading.value = false
  }
}

watch(target, refresh)

onMounted(() => {
  refresh()
})
</script>
