<template>
  <div>
    <NSpace
      justify="end"
      class="mb-2"
    >
      <NButton
        type="primary"
        @click="openCreate"
      >
        新建 worktree
      </NButton>
    </NSpace>
    <NDataTable
      :columns="columns"
      :data="store.worktrees"
    />

    <NModal
      :show="showCreate"
      preset="card"
      title="新建 worktree"
      :style="{ width: '420px' }"
      @close="showCreate = false"
    >
      <NForm>
        <NFormItem
          label="分支"
          required
        >
          <NInput v-model:value="newBranch" />
        </NFormItem>
        <NFormItem label="基线分支（默认 default_branch）">
          <NSelect
            v-model:value="newBase"
            :options="baseBranchOptions"
            :loading="branchesLoading"
            clearable
            filterable
            tag
            placeholder="默认使用 default_branch"
          />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace justify="end">
          <NButton @click="showCreate = false">
            取消
          </NButton>
          <NButton
            type="primary"
            :loading="creating"
            @click="onCreate"
          >
            创建
          </NButton>
        </NSpace>
      </template>
    </NModal>

    <CommitDialog
      v-if="commitFor"
      target="worktree"
      :target-id="commitFor.id"
      @close="commitFor = null"
      @committed="commitFor = null"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, h } from 'vue'
import {
  NDataTable,
  NButton,
  NSpace,
  NTag,
  NModal,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  useMessage,
  useDialog,
} from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import { useWorkspacesStore } from '@/stores/workspaces'
import { workspacesApi } from '@/api/workspaces'
import CommitDialog from './CommitDialog.vue'
import type { Workspace, Worktree, WorktreeStatus } from '@/api/types'

const props = defineProps<{ ws: Workspace }>()
const store = useWorkspacesStore()
const msg = useMessage()
const dialog = useDialog()

const showCreate = ref<boolean>(false)
const creating = ref<boolean>(false)
const newBranch = ref<string>('')
const newBase = ref<string | null>(null)

const commitFor = ref<Worktree | null>(null)

// Branch list for base_branch selector
const branches = ref<string[]>([])
const branchesLoading = ref(false)

const STATUS_TAG_TYPE: Record<WorktreeStatus, 'warning' | 'error' | 'default'> = {
  active: 'warning',
  pruning: 'error',
  idle: 'default',
}

async function openCreate() {
  showCreate.value = true
  newBranch.value = ''
  newBase.value = null
  // Fetch branch list when dialog opens
  branchesLoading.value = true
  try {
    branches.value = await workspacesApi.listBranches(props.ws.id)
  } catch {
    // Silently fail — user can still type manually
    branches.value = []
  } finally {
    branchesLoading.value = false
  }
}

const baseBranchOptions = computed(() =>
  branches.value.map((b) => ({ label: b, value: b })),
)

async function onCreate() {
  if (!newBranch.value.trim()) {
    msg.error('分支名为必填')
    return
  }
  creating.value = true
  try {
    await store.createWorktree(props.ws.id, {
      branch: newBranch.value,
      base_branch: newBase.value || undefined,
    })
    showCreate.value = false
    newBranch.value = ''
    newBase.value = null
  } catch (e: unknown) {
    msg.error('创建失败：' + (e instanceof Error ? e.message : String(e)))
  } finally {
    creating.value = false
  }
}

async function onAcquire(wt: Worktree) {
  try {
    await store.acquire(wt.id)
  } catch (e: unknown) {
    msg.error('占用失败：' + (e instanceof Error ? e.message : String(e)))
  }
}

async function onRelease(wt: Worktree) {
  try {
    await store.release(wt.id)
  } catch (e: unknown) {
    msg.error('释放失败：' + (e instanceof Error ? e.message : String(e)))
  }
}

function onDelete(wt: Worktree) {
  dialog.warning({
    title: '确认删除',
    content: `删除 worktree "${wt.branch}" 将移除磁盘文件夹，不可恢复。`,
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await store.deleteWorktree(wt.id)
      } catch (e: unknown) {
        msg.error('删除失败：' + (e instanceof Error ? e.message : String(e)))
      }
    },
  })
}

async function onPush(wt: Worktree) {
  try {
    await store.pushOnWorktree(wt.id)
    msg.success('已 push')
  } catch (e: unknown) {
    msg.error('push 失败：' + (e instanceof Error ? e.message : String(e)))
  }
}

const columns = computed<DataTableColumns<Worktree>>(() => [
  { title: '分支', key: 'branch' },
  {
    title: '状态',
    key: 'status',
    render(row: Worktree) {
      return h(
        NTag,
        { type: STATUS_TAG_TYPE[row.status] ?? 'default', size: 'small' },
        { default: () => row.status },
      )
    },
  },
  { title: '占用者', key: 'active_holder' },
  {
    title: '操作',
    key: 'ops',
    render(row: Worktree) {
      return h(
        NSpace,
        { size: 'small' },
        {
          default: () => [
            h(
              NButton,
              { size: 'tiny', onClick: () => (commitFor.value = row) },
              { default: () => '提交' },
            ),
            h(
              NButton,
              { size: 'tiny', onClick: () => onPush(row) },
              { default: () => 'Push' },
            ),
            row.status === 'idle'
              ? h(
                  NButton,
                  { size: 'tiny', type: 'primary', onClick: () => onAcquire(row) },
                  { default: () => '占用' },
                )
              : h(
                  NButton,
                  { size: 'tiny', onClick: () => onRelease(row) },
                  { default: () => '释放' },
                ),
            h(
              NButton,
              { size: 'tiny', type: 'error', onClick: () => onDelete(row) },
              { default: () => '删除' },
            ),
          ],
        },
      )
    },
  },
])
</script>
