<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import './database/database.css'

// 模拟知识库数据
const knowledgeBases = ref([
  {
    id: '1',
    name: 'Product Documentation',
    description: 'Product user manual and API docs',
    document_count: 156,
    chunk_count: 1248,
    created_at: '2024-01-15T10:30:00Z',
    status: 'ready'
  },
  {
    id: '2',
    name: 'Company Policies',
    description: 'Internal company policies and procedures',
    document_count: 42,
    chunk_count: 320,
    created_at: '2024-01-20T14:20:00Z',
    status: 'ready'
  },
  {
    id: '3',
    name: 'Technical Wiki',
    description: 'Engineering documentation and RFCs',
    document_count: 89,
    chunk_count: 756,
    created_at: '2024-02-01T09:15:00Z',
    status: 'processing'
  },
])

const loading = ref(false)
const searchQuery = ref('')

// 筛选知识库
const filteredKnowledgeBases = () => {
  if (!searchQuery.value) return knowledgeBases.value
  const query = searchQuery.value.toLowerCase()
  return knowledgeBases.value.filter(kb =>
    kb.name.toLowerCase().includes(query) ||
    kb.description.toLowerCase().includes(query)
  )
}

// 新建知识库
const showCreateDialog = ref(false)
const newKbForm = ref({
  name: '',
  description: '',
})

const createKnowledgeBase = () => {
  if (!newKbForm.value.name) {
    ElMessage.warning('Please enter knowledge base name')
    return
  }
  knowledgeBases.value.push({
    id: Date.now().toString(),
    name: newKbForm.value.name,
    description: newKbForm.value.description,
    document_count: 0,
    chunk_count: 0,
    created_at: new Date().toISOString(),
    status: 'ready'
  })
  newKbForm.value = { name: '', description: '' }
  showCreateDialog.value = false
  ElMessage.success('Knowledge base created successfully')
}

const cancelCreate = () => {
  newKbForm.value = { name: '', description: '' }
  showCreateDialog.value = false
}

// 编辑知识库
const showEditDialog = ref(false)
const editForm = ref({
  id: '',
  name: '',
  description: '',
})

const openEdit = (kb: any) => {
  editForm.value = {
    id: kb.id,
    name: kb.name,
    description: kb.description
  }
  showEditDialog.value = true
}

const saveEdit = () => {
  const kb = knowledgeBases.value.find(k => k.id === editForm.value.id)
  if (kb) {
    kb.name = editForm.value.name
    kb.description = editForm.value.description
  }
  showEditDialog.value = false
  ElMessage.success('Knowledge base updated successfully')
}

const cancelEdit = () => {
  showEditDialog.value = false
}

// 删除知识库
const deleteKb = (id: string) => {
  const index = knowledgeBases.value.findIndex(k => k.id === id)
  if (index > -1) {
    knowledgeBases.value.splice(index, 1)
    ElMessage.success('Knowledge base deleted')
  }
}

// 查看详情
const viewDetail = (kb: any) => {
  ElMessage.info(`Viewing ${kb.name}`)
}
</script>

<template>
  <div class="p-6 min-h-screen">
    <!-- 顶部导航 -->
    <div class="flex justify-between items-center mb-6">
      <div class="flex items-center gap-2">
        <i class="fa-solid fa-brain text-gray-400"></i>
        <span class="font-medium">Knowledge Base</span>
      </div>
      <button @click="showCreateDialog = true" class="btn-primary">
        <i class="fa-solid fa-plus"></i>
        New Knowledge Base
      </button>
    </div>

    <!-- 搜索 -->
    <div class="flex gap-4 mb-6">
      <div class="flex-1 relative">
        <i class="fa-solid fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
        <input
          v-model="searchQuery"
          type="text"
          placeholder="Search knowledge bases by name or description..."
          class="search-input w-full"
        >
      </div>
    </div>

    <!-- Knowledge Base 列表 -->
    <div class="bg-dark-700 rounded-xl overflow-hidden">
      <div v-if="loading" class="py-12 text-center text-gray-400">
        <i class="fa-solid fa-circle-notch fa-spin text-2xl mb-2"></i>
        <p>Loading...</p>
      </div>
      <table v-else-if="filteredKnowledgeBases().length > 0" class="w-full">
        <thead class="bg-dark-600">
          <tr>
            <th class="text-left px-5 py-3 text-sm font-medium text-gray-400">Name</th>
            <th class="text-center px-5 py-3 text-sm font-medium text-gray-400">Documents</th>
            <th class="text-center px-5 py-3 text-sm font-medium text-gray-400">Chunks</th>
            <th class="text-center px-5 py-3 text-sm font-medium text-gray-400">Status</th>
            <th class="text-center px-5 py-3 text-sm font-medium text-gray-400">Created</th>
            <th class="text-center px-5 py-3 text-sm font-medium text-gray-400">Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="kb in filteredKnowledgeBases()" :key="kb.id" class="table-row">
            <td class="px-5 py-4">
              <div class="font-medium">{{ kb.name }}</div>
              <div class="text-sm text-gray-500">{{ kb.description }}</div>
            </td>
            <td class="px-5 py-4 text-center">
              <span class="text-primary-cyan">{{ kb.document_count }}</span>
            </td>
            <td class="px-5 py-4 text-center text-gray-400 text-sm">
              {{ kb.chunk_count }}
            </td>
            <td class="px-5 py-4 text-center">
              <span v-if="kb.status === 'ready'" class="bg-primary-success/20 text-primary-success px-2 py-1 rounded text-sm">
                Ready
              </span>
              <span v-else-if="kb.status === 'processing'" class="bg-primary-warning/20 text-primary-warning px-2 py-1 rounded text-sm">
                Processing
              </span>
            </td>
            <td class="px-5 py-4 text-center text-gray-400 text-sm">
              {{ kb.created_at?.split('T')[0] }}
            </td>
            <td class="px-5 py-4">
              <div class="flex items-center justify-center gap-2">
                <button
                  @click="viewDetail(kb)"
                  class="p-2 rounded-lg hover:bg-dark-600 transition-colors"
                  title="View"
                >
                  <i class="fa-solid fa-eye text-gray-400"></i>
                </button>
                <button
                  @click="openEdit(kb)"
                  class="p-2 rounded-lg hover:bg-dark-600 transition-colors"
                  title="Edit"
                >
                  <i class="fa-solid fa-pen text-gray-400"></i>
                </button>
                <button
                  @click="deleteKb(kb.id)"
                  class="p-2 rounded-lg hover:bg-dark-600 transition-colors"
                  title="Delete"
                >
                  <i class="fa-solid fa-trash text-gray-400 hover:text-primary-danger"></i>
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 空状态 -->
      <div v-else class="empty-box">
        <div class="empty-icon">
          <i class="fa-solid fa-brain"></i>
        </div>
        <p class="empty-text">No knowledge bases found</p>
        <p class="empty-tip">Click "New Knowledge Base" to create one</p>
      </div>
    </div>

    <!-- 新建知识库弹窗 -->
    <el-dialog
      v-model="showCreateDialog"
      title="Create Knowledge Base"
      width="500px"
      :close-on-click-modal="false"
      class="kb-dialog"
    >
      <p class="dialog-desc">Create a new knowledge base to store your documents</p>

      <el-form label-position="top" class="kb-form">
        <el-form-item label="Name">
          <el-input v-model="newKbForm.name" placeholder="Enter knowledge base name" />
        </el-form-item>
        <el-form-item label="Description">
          <el-input v-model="newKbForm.description" type="textarea" :rows="3" placeholder="Enter description" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button text @click="cancelCreate">Cancel</el-button>
          <el-button type="primary" @click="createKnowledgeBase">Confirm</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑知识库弹窗 -->
    <el-dialog
      v-model="showEditDialog"
      title="Edit Knowledge Base"
      width="500px"
      :close-on-click-modal="false"
      class="kb-dialog"
    >
      <p class="dialog-desc">Edit knowledge base information</p>

      <el-form label-position="top" class="kb-form">
        <el-form-item label="Name">
          <el-input v-model="editForm.name" placeholder="Enter knowledge base name" />
        </el-form-item>
        <el-form-item label="Description">
          <el-input v-model="editForm.description" type="textarea" :rows="3" placeholder="Enter description" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button text @click="cancelEdit">Cancel</el-button>
          <el-button type="primary" @click="saveEdit">Save</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 按钮样式 */
.btn-primary {
  background-color: #f97316;
  border: none;
  color: white;
  padding: 10px 16px;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  transition: all 0.2s;
}

.btn-primary:hover {
  background-color: #ea580c;
}

/* 搜索框 */
.search-input {
  background-color: #171922;
  border: 1px solid #374151;
  color: white;
  padding: 10px 12px 10px 36px;
  border-radius: 8px;
  outline: none;
  transition: border-color 0.2s;
}

.search-input:focus {
  border-color: #f97316;
}

.search-input::placeholder {
  color: #6b7280;
}

/* 表格样式 */
.bg-dark-700 {
  background-color: #1f2937;
}

.bg-dark-600 {
  background-color: #111827;
}

.table-row {
  border-bottom: 1px solid #374151;
  transition: background-color 0.2s;
}

.table-row:hover {
  background-color: #374151;
}

/* 空状态 - 使用 database.css 中的样式 */
.empty-box {
  min-height: 340px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.empty-icon {
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #1f2937, #111827);
  border-radius: 24px;
  margin-bottom: 20px;
}

.empty-icon i {
  font-size: 40px;
  color: #6b7280;
}

.empty-text {
  color: #d1d5db;
  font-size: 1.25rem;
  font-weight: 500;
  margin-bottom: 8px;
}

.empty-tip {
  color: #6b7280;
  font-size: 0.875rem;
}

/* 弹窗样式 */
.kb-dialog :deep(.el-dialog) {
  background-color: #1f2937;
  border-radius: 12px;
  border: 1px solid #374151;
}

.kb-dialog :deep(.el-dialog__header) {
  padding: 20px 24px;
  border-bottom: 1px solid #374151;
}

.kb-dialog :deep(.el-dialog__title) {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.kb-dialog :deep(.el-dialog__headerbtn) {
  top: 20px;
  right: 20px;
}

.kb-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: #9ca3af;
}

.kb-dialog :deep(.el-dialog__headerbtn:hover .el-dialog__close) {
  color: #f97316;
}

.kb-dialog :deep(.el-dialog__body) {
  padding: 24px;
}

.kb-dialog :deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #374151;
}

.dialog-desc {
  font-size: 14px;
  color: #9ca3af;
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.kb-form :deep(.el-form-item__label) {
  color: #d1d5db;
  font-size: 14px;
}

.kb-form :deep(.el-input__wrapper) {
  background-color: #171922;
  border: 1px solid #374151;
  box-shadow: none;
}

.kb-form :deep(.el-input__inner) {
  color: white;
}

.kb-form :deep(.el-textarea__inner) {
  background-color: #171922;
  border: 1px solid #374151;
  color: white;
  box-shadow: none;
}

.kb-dialog :deep(.el-button--primary) {
  background-color: #f97316;
  border-color: #f97316;
}

.kb-dialog :deep(.el-button--primary:hover) {
  background-color: #ea580c;
  border-color: #ea580c;
}
</style>
