<template>
  <div class="space-y-4">
    <NSpace align="center">
      <NButton type="primary" size="small" @click="showCreate = true"> 新建 PR </NButton>
      <NButton size="small" :loading="loading" @click="refresh"> 刷新 </NButton>
    </NSpace>

    <NDataTable :columns="columns" :data="rows" :loading="loading" size="small" :scroll-x="1000" />

    <NModal v-model:show="showCreate" preset="card" title="新建 Pull Request" style="width: 520px">
      <NForm>
        <NFormItem label="源分支">
          <NInput v-model:value="form.source_branch" placeholder="feature/x" />
        </NFormItem>
        <NFormItem label="目标分支 (留空用默认分支)">
          <NInput v-model:value="form.target_branch" :placeholder="ws.default_branch" />
        </NFormItem>
        <NFormItem label="标题">
          <NInput v-model:value="form.title" />
        </NFormItem>
        <NFormItem label="描述">
          <NInput v-model:value="form.description" type="textarea" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace justify="end">
          <NButton @click="showCreate = false"> 取消 </NButton>
          <NButton type="primary" :loading="creating" @click="create"> 创建 </NButton>
        </NSpace>
      </template>
    </NModal>
  </div>
</template>

<script setup lang="ts">
import { computed, h, onMounted, ref, watch } from 'vue'
import {
  NButton,
  NDataTable,
  NModal,
  NForm,
  NFormItem,
  NInput,
  NSpace,
  NTag,
  useMessage,
} from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'

import { changeRequestsApi } from '@/api/changeRequests'
import type { ChangeRequest, Workspace } from '@/api/types'

const props = defineProps<{ ws: Workspace }>()
const msg = useMessage()

const rows = ref<ChangeRequest[]>([])
const loading = ref(false)
const showCreate = ref(false)
const creating = ref(false)
const form = ref({ source_branch: '', target_branch: '', title: '', description: '' })

async function refresh() {
  loading.value = true
  try {
    rows.value = await changeRequestsApi.list(props.ws.id)
  } catch (e: unknown) {
    msg.error('加载 PR 列表失败：' + (e instanceof Error ? e.message : String(e)))
  } finally {
    loading.value = false
  }
}

async function create() {
  creating.value = true
  try {
    await changeRequestsApi.create(props.ws.id, {
      source_branch: form.value.source_branch,
      target_branch: form.value.target_branch || undefined,
      title: form.value.title,
      description: form.value.description || undefined,
    })
    msg.success('已创建 PR')
    showCreate.value = false
    form.value = { source_branch: '', target_branch: '', title: '', description: '' }
    await refresh()
  } catch (e: unknown) {
    msg.error('创建失败：' + (e instanceof Error ? e.message : String(e)))
  } finally {
    creating.value = false
  }
}

async function review(cr: ChangeRequest, verdict: 'approved' | 'changes_requested') {
  try {
    await changeRequestsApi.review(cr.id, { verdict })
    msg.success('已提交评审')
    await refresh()
  } catch (e: unknown) {
    msg.error('评审失败：' + (e instanceof Error ? e.message : String(e)))
  }
}

async function merge(cr: ChangeRequest) {
  try {
    await changeRequestsApi.merge(cr.id, {})
    msg.success('已合并')
    await refresh()
  } catch (e: unknown) {
    msg.error('合并失败：' + (e instanceof Error ? e.message : String(e)))
  }
}

async function sync(cr: ChangeRequest) {
  try {
    await changeRequestsApi.sync(cr.id)
    await refresh()
  } catch (e: unknown) {
    msg.error('同步失败：' + (e instanceof Error ? e.message : String(e)))
  }
}

function verdictColor(v: string): 'default' | 'success' | 'warning' | 'error' {
  if (v === 'approved') return 'success'
  if (v === 'changes_requested') return 'warning'
  if (v === 'rejected') return 'error'
  return 'default'
}

function ciColor(v: string): 'default' | 'success' | 'warning' | 'error' {
  if (v === 'success') return 'success'
  if (v === 'failure') return 'error'
  if (v === 'pending') return 'warning'
  return 'default'
}

const columns = computed<DataTableColumns<ChangeRequest>>(() => [
  { title: '#', key: 'number', width: 50 },
  { title: '标题', key: 'title', ellipsis: { tooltip: true } },
  {
    title: '分支',
    key: 'branch',
    render: (r) => `${r.source_branch} → ${r.target_branch}`,
  },
  {
    title: '状态',
    key: 'state',
    render: (r) => h(NTag, { size: 'small' }, { default: () => r.state }),
  },
  {
    title: '评审',
    key: 'review_verdict',
    render: (r) =>
      h(
        NTag,
        { size: 'small', type: verdictColor(r.review_verdict) },
        { default: () => r.review_verdict },
      ),
  },
  {
    title: 'CI',
    key: 'ci_state',
    render: (r) =>
      h(NTag, { size: 'small', type: ciColor(r.ci_state) }, { default: () => r.ci_state }),
  },
  {
    title: '操作',
    key: 'actions',
    width: 320,
    render: (r) =>
      h(
        NSpace,
        { size: 'small' },
        {
          default: () => [
            h(
              NButton,
              { size: 'tiny', disabled: r.state !== 'open', onClick: () => review(r, 'approved') },
              { default: () => '批准' },
            ),
            h(
              NButton,
              {
                size: 'tiny',
                disabled: r.state !== 'open',
                onClick: () => review(r, 'changes_requested'),
              },
              { default: () => '请求修改' },
            ),
            h(
              NButton,
              {
                size: 'tiny',
                type: 'primary',
                disabled: r.state !== 'open' || r.review_verdict !== 'approved',
                onClick: () => merge(r),
              },
              { default: () => '合并' },
            ),
            h(NButton, { size: 'tiny', onClick: () => sync(r) }, { default: () => '同步' }),
          ],
        },
      ),
  },
])

onMounted(refresh)
watch(() => props.ws.id, refresh)
</script>
