<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import './knowledge/knowledge.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 createStep = ref(1)
const newKbForm = ref({
  name: '',
  description: '',
})
const embeddingConfig = ref({
  provider: '',
  model: '',
})

const openCreateDialog = () => {
  createStep.value = 1
  newKbForm.value = { name: '', description: '' }
  embeddingConfig.value = { provider: '', model: '' }
  showCreateDialog.value = true
}

const nextStep = () => {
  if (!newKbForm.value.name) {
    ElMessage.warning('Please enter knowledge base name')
    return
  }
  createStep.value = 2
}

const prevStep = () => {
  createStep.value = 1
}

const createKnowledgeBase = () => {
  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: '' }
  embeddingConfig.value = { provider: '', model: '' }
  showCreateDialog.value = false
  ElMessage.success('Knowledge base created successfully')
}

const cancelCreate = () => {
  newKbForm.value = { name: '', description: '' }
  embeddingConfig.value = { provider: '', model: '' }
  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="openCreateDialog" 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 transition-colors hover:bg-dark-600"
                  title="View"
                >
                  <i class="fa-solid fa-eye text-gray-400 hover:text-primary-danger"></i>
                </button>
                <button
                  @click="openEdit(kb)"
                  class="p-2 rounded-lg transition-colors hover:bg-dark-600"
                  title="Edit"
                >
                  <i class="fa-solid fa-pen text-gray-400 hover:text-primary-danger"></i>
                </button>
                <button
                  @click="deleteKb(kb.id)"
                  class="p-2 rounded-lg transition-colors hover:bg-dark-600"
                  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="创建知识库"
      width="1100px"
      :close-on-click-modal="false"
      :show-close="false"
      class="kb-dialog kb-create-dialog"
    >
      <div class="create-layout">
        <!-- 左侧：选项列表 -->
        <div class="sidebar">
          <div
            class="menu-item"
            :class="{ active: createStep === 1 }"
            @click="createStep = 1"
          >
            <i class="fa-solid fa-layer-group menu-icon"></i>
            <div class="menu-content">
              <span class="menu-title">基本信息</span>
              <span class="menu-desc">知识库名称和描述</span>
            </div>
            <i v-if="createStep === 1" class="fa-solid fa-chevron-right menu-arrow"></i>
          </div>
          <div
            class="menu-item"
            :class="{ active: createStep === 2 }"
            @click="createStep = 2"
          >
            <i class="fa-solid fa-brain menu-icon"></i>
            <div class="menu-content">
              <span class="menu-title">Embedding 配置</span>
              <span class="menu-desc">向量化和检索设置</span>
            </div>
            <i v-if="createStep === 2" class="fa-solid fa-chevron-right menu-arrow"></i>
          </div>
        </div>

        <!-- 右侧：内容区 -->
        <div class="content">
          <!-- 基本信息 -->
          <div v-if="createStep === 1" class="form-content">
            <div class="section-header">
              <i class="fa-solid fa-layer-group section-icon"></i>
              <span class="section-title">基本信息</span>
            </div>
            <el-form label-position="top" class="kb-form">
              <el-form-item label="名称" required>
                <el-input v-model="newKbForm.name" placeholder="请输入知识库名称" />
              </el-form-item>
              <el-form-item label="描述">
                <el-input v-model="newKbForm.description" type="textarea" :rows="4" placeholder="请输入知识库描述" />
              </el-form-item>
            </el-form>
          </div>

          <!-- Embedding 配置 -->
          <div v-if="createStep === 2" class="form-content">
            <div class="section-header">
              <i class="fa-solid fa-brain section-icon"></i>
              <span class="section-title">Embedding 配置</span>
            </div>
            <el-form label-position="top" class="kb-form">
              <el-form-item label="Embedding Provider">
                <el-select v-model="embeddingConfig.provider" placeholder="请选择 Embedding 服务商" class="w-full">
                  <el-option label="OpenAI" value="openai">
                    <div class="provider-option">
                      <i class="fa-solid fa-robot"></i>
                      <span>OpenAI</span>
                    </div>
                  </el-option>
                  <el-option label="Ollama" value="ollama">
                    <div class="provider-option">
                      <i class="fa-solid fa-microchip"></i>
                      <span>Ollama</span>
                    </div>
                  </el-option>
                  <el-option label="Azure OpenAI" value="azure">
                    <div class="provider-option">
                      <i class="fa-brands fa-microsoft"></i>
                      <span>Azure OpenAI</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="Embedding Model">
                <el-input v-model="embeddingConfig.model" placeholder="如：text-embedding-ada-002" />
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <div class="footer-left">
            <span class="step-hint">填写完基本信息后，点击下一步继续配置</span>
          </div>
          <div class="footer-right">
            <el-button @click="cancelCreate" class="cancel-btn">取消</el-button>
            <el-button v-if="createStep === 2" @click="createStep = 1" class="prev-btn">
              <i class="fa-solid fa-arrow-left"></i>
              上一步
            </el-button>
            <el-button v-if="createStep === 1" @click="createStep = 2" class="next-btn">
              下一步
              <i class="fa-solid fa-arrow-right"></i>
            </el-button>
            <el-button v-if="createStep === 2" @click="createKnowledgeBase" class="confirm-btn">
              <i class="fa-solid fa-plus"></i>
              创建
            </el-button>
          </div>
        </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>
