<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import apiClient from '@/api/client'
import { copyToClipboard } from '@/utils/clipboard'

const router = useRouter()
const kbs = ref<any[]>([])
const loading = ref(false)
const showCreate = ref(false)
const createForm = ref({ name: '', description: '' })
const createLoading = ref(false)

onMounted(() => {
  loadKbs()
})

async function loadKbs() {
  loading.value = true
  try {
    const { data } = await apiClient.get('/knowledge-bases')
    kbs.value = data.items
  } catch { /* ignore */ }
  loading.value = false
}

async function handleCreate() {
  if (!createForm.value.name.trim()) {
    ElMessage.warning('请输入知识库名称。')
    return
  }
  createLoading.value = true
  try {
    const { data } = await apiClient.post('/knowledge-bases', createForm.value)
    ElMessage.success('知识库创建成功！')
    showCreate.value = false
    createForm.value = { name: '', description: '' }
    router.push(`/knowledge-bases/${data.id}`)
  } catch { /* ignore */ }
  createLoading.value = false
}

async function handleDelete(kb: any) {
  try {
    await ElMessageBox.confirm(`确定删除知识库「${kb.name}」？`, '确认删除', { type: 'warning' })
    await apiClient.delete(`/knowledge-bases/${kb.id}`)
    ElMessage.success('已删除。')
    loadKbs()
  } catch { /* ignore */ }
}

async function handleToggle(kb: any) {
  const action = kb.enabled ? 'disable' : 'enable'
  await apiClient.post(`/knowledge-bases/${kb.id}/${action}`)
  ElMessage.success(kb.enabled ? '已禁用。' : '已启用。')
  loadKbs()
}

async function handleCopyLink(kb: any) {
  try {
    const { data } = await apiClient.get(`/knowledge-bases/${kb.id}/link`)
    const url = `${window.location.origin}${data.ai_url}`
    const success = await copyToClipboard(url)
    if (success) {
      ElMessage.success('AI 链接已复制到剪贴板！')
    } else {
      ElMessage.error('复制失败，请稍后重试。')
    }
  } catch { /* ignore */ }
}
</script>

<template>
  <div>
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px">
      <h1 style="margin: 0">知识库</h1>
      <el-button type="primary" @click="showCreate = true">创建知识库</el-button>
    </div>

    <el-table :data="kbs" v-loading="loading" style="width: 100%">
      <el-table-column prop="name" label="名称" min-width="200">
        <template #default="{ row }">
          <router-link :to="`/knowledge-bases/${row.id}`" style="color: #409eff; text-decoration: none">
            {{ row.name }}
          </router-link>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
      <el-table-column prop="document_count" label="文档数" width="100" align="center" />
      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.enabled ? 'success' : 'danger'" size="small">
            {{ row.enabled ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" align="center">
        <template #default="{ row }">
          <el-button size="small" @click="handleCopyLink(row)">复制链接</el-button>
          <el-button size="small" @click="handleToggle(row)">
            {{ row.enabled ? '禁用' : '启用' }}
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建对话框 -->
    <el-dialog v-model="showCreate" title="创建知识库" width="500px">
      <el-form :model="createForm" label-position="top">
        <el-form-item label="名称" required>
          <el-input v-model="createForm.name" placeholder="例如：公司知识库" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="createForm.description" type="textarea" :rows="3" placeholder="可选描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreate = false">取消</el-button>
        <el-button type="primary" :loading="createLoading" @click="handleCreate">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>
