<script setup lang="ts">
import { onMounted } from 'vue'
import { useSkills } from './skill/skill'
import { Edit, Trash2, Wand2, Plus, Search, X, FolderInput, Play, Pause } from 'lucide-vue-next'
import '@/views/database/database.css'

const {
  skillsLoading,
  searchQuery,
  filterStatus,
  isEditing,
  isCreating,
  isEditingContent,
  editForm,
  newSkillForm,
  newSkillContent,
  filteredSkills,
  fetchSkills,
  openCreate,
  closeCreate,
  goToEditContent,
  closeEditContent,
  saveNewSkill,
  openEdit,
  closeEdit,
  saveEdit,
  toggleStatus,
  deleteSkill,
  // 导入相关 - 从 useSkills 引入
  fileInputRef,
  isImporting,
  isImportingDialog,
  importFileName,
  importSkillName,
  importSkillDesc,
  importSkillContent,
  isImportStep2,
  openImportDialog,
  closeImportDialog,
  handleFileChange,
  submitImport,
  handleFolderSelect,
  // 下拉菜单
  showDropdown,
  onDropdownEnter,
  onDropdownLeave,
} = useSkills()

// 页面加载时获取技能列表
onMounted(() => {
  fetchSkills()
})
</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">
        <Wand2 class="w-5 h-5 text-orange-500" />
        <span class="font-medium">Skills</span>
      </div>

      <!-- 新建按钮（带下拉菜单） -->
      <div class="relative" @mouseenter="onDropdownEnter" @mouseleave="onDropdownLeave">
        <button class="flex items-center gap-2 px-4 py-2 rounded-lg bg-gradient-to-r from-orange-500 to-amber-500 text-white text-sm font-medium hover:from-orange-400 hover:to-amber-400 transition-all">
          <Plus class="w-4 h-4" />
          New Skill
          <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
          </svg>
        </button>
        <!-- 下拉菜单 -->
        <div v-if="showDropdown" class="absolute right-0 top-full mt-2 w-48 bg-dark-700 border border-dark-500 rounded-lg shadow-xl overflow-hidden z-50" @mouseenter="onDropdownEnter" @mouseleave="onDropdownLeave">
          <button
            @click="openCreate"
            class="w-full flex items-center gap-3 px-4 py-3 hover:bg-dark-600 transition-colors text-left"
          >
            <Plus class="w-4 h-4 text-orange-400" />
            <div>
              <div class="text-sm text-white">Create Skill</div>
              <div class="text-xs text-gray-400">Manual create</div>
            </div>
          </button>
          <button
            @click="openImportDialog"
            class="w-full flex items-center gap-3 px-4 py-3 hover:bg-dark-600 transition-colors text-left"
          >
            <FolderInput class="w-4 h-4 text-blue-400" />
            <div>
              <div class="text-sm text-white">Import Skill</div>
              <div class="text-xs text-gray-400">From local folder</div>
            </div>
          </button>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="flex gap-4 mb-6">
      <div class="flex-1 relative">
        <Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
        <input
          v-model="searchQuery"
          type="text"
          placeholder="Search skills by name, type or description..."
          class="search-input w-full"
        >
      </div>
      <el-select v-model="filterStatus" placeholder="Select" class="w-40" size="large">
        <el-option label="All Status" value="all" />
        <el-option label="Running" value="running" />
        <el-option label="Stopped" value="stopped" />
        <el-option label="Error" value="error" />
      </el-select>
    </div>

    <!-- Skills 列表 -->
    <div class="bg-dark-700 rounded-xl overflow-hidden shadow-lg">
      <table v-if="filteredSkills.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 w-1/3">Skill Name</th>
            <th class="text-center px-5 py-3 text-sm font-medium text-gray-400">Category</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="skill in filteredSkills" :key="skill.id" class="table-row">
            <td class="px-5 py-4">
              <div class="flex gap-3">
                <div class="w-10 h-10 rounded-lg bg-orange-500/20 flex items-center justify-center flex-shrink-0 self-center">
                  <Wand2 class="w-5 h-5 text-orange-400" />
                </div>
                <div class="min-w-0 self-center">
                  <div class="font-medium">{{ skill.skill_name }}</div>
                  <div class="text-sm text-gray-500 line-clamp-2 mt-0.5">{{ skill.skill_desc || '-' }}</div>
                </div>
              </div>
            </td>
            <td class="px-5 py-4 text-center">
              <span class="text-gray-400 text-sm">{{ skill.skill_type === 'system' ? 'System' : 'User' }}</span>
            </td>
            <td class="px-5 py-4 text-center">
              <span class="inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-xs" :class="skill.status === 'active' ? 'bg-green-500/20 text-green-400' : 'bg-gray-500/20 text-gray-400'">
                <span class="w-1.5 h-1.5 rounded-full" :class="skill.status === 'active' ? 'bg-green-500' : 'bg-gray-400'"></span>
                <span class="capitalize">{{ skill.status }}</span>
              </span>
            </td>
            <td class="px-5 py-4 text-center text-gray-400 text-sm">{{ skill.created_at ? new Date(skill.created_at).toLocaleDateString() : '-' }}</td>
            <td class="px-5 py-4">
              <div class="flex items-center justify-center gap-2">
                <button
                  @click="toggleStatus(skill)"
                  class="btn-icon"
                  :title="skill.status === 'active' ? 'Pause' : 'Start'"
                >
                  <Pause v-if="skill.status === 'active'" class="w-4 h-4 text-gray-400 hover:text-yellow-400" />
                  <Play v-else class="w-4 h-4 text-gray-400 hover:text-green-400" />
                </button>
                <button @click="openEdit(skill)" class="btn-icon" title="Edit">
                  <Edit class="w-4 h-4 text-gray-400 hover:text-white" />
                </button>
                <button @click="deleteSkill(skill.id)" class="btn-icon" title="Delete">
                  <Trash2 class="w-4 h-4 text-gray-400 hover:text-red-400" />
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 空状态 -->
      <div v-else class="empty-box">
        <div class="empty-icon">
          <Wand2 class="w-12 h-12" />
        </div>
        <p class="empty-text">No skills found</p>
        <p class="empty-tip">Click "New Skill" to add a skill</p>
      </div>
    </div>

    <!-- 编辑弹窗 -->
    <Teleport to="body">
      <div v-if="isEditing" class="fixed inset-0 bg-black/60 flex items-center justify-center z-50 modal-overlay">
        <div class="bg-dark-700 rounded-2xl w-full max-w-lg border border-dark-500 shadow-2xl modal-content">
          <div class="flex items-center justify-between p-5 border-b border-dark-500">
            <h3 class="text-lg font-semibold">Edit Skill</h3>
            <button @click="closeEdit" class="btn-icon">
              <X class="w-5 h-5" />
            </button>
          </div>

          <div class="p-5 space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">Skill Name</label>
              <input v-model="editForm.skill_name" type="text" class="input-field">
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">Category</label>
              <select v-model="editForm.skill_type" class="input-field">
                <option value="user">User</option>
                <option value="system">System</option>
              </select>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">Description</label>
              <textarea v-model="editForm.skill_desc" rows="2" class="input-field resize-none"></textarea>
            </div>
          </div>

          <div class="flex items-center justify-end gap-3 p-5 border-t border-dark-500">
            <button @click="closeEdit" class="btn-secondary">Cancel</button>
            <button @click="saveEdit" class="btn-primary">Save Changes</button>
          </div>
        </div>
      </div>
    </Teleport>

    <!-- 新建弹窗 -->
    <Teleport to="body">
      <div v-if="isCreating" class="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4 modal-overlay">
        <div class="bg-dark-800 rounded-2xl w-full max-w-lg border border-dark-600 shadow-2xl overflow-hidden modal-content">
          <div class="flex items-center justify-between p-5 border-b border-dark-600 bg-dark-700/50">
            <div class="flex items-center gap-3">
              <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-orange-500 to-red-500 flex items-center justify-center">
                <Wand2 class="w-5 h-5 text-white" />
              </div>
              <div>
                <h3 class="text-xl font-semibold text-white">Create New Skill</h3>
                <p class="text-sm text-gray-400">Configure your skill</p>
              </div>
            </div>
            <button @click="closeCreate" class="btn-icon">
              <X class="w-5 h-5" />
            </button>
          </div>

          <div class="p-5 space-y-4 max-h-[60vh] overflow-y-auto">
            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">Skill Name</label>
              <input v-model="newSkillForm.skill_name" type="text" placeholder="Enter skill name..." class="input-field">
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">Category</label>
              <select v-model="newSkillForm.skill_type" class="input-field">
                <option value="user">User</option>
                <option value="system">System</option>
              </select>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">Description</label>
              <textarea v-model="newSkillForm.skill_desc" rows="2" placeholder="Describe this skill..." class="input-field resize-none"></textarea>
            </div>
          </div>

          <div class="flex items-center justify-end gap-3 p-5 border-t border-dark-600 bg-dark-700/50">
            <button @click="closeCreate" class="btn-secondary">Cancel</button>
            <button @click="goToEditContent" :disabled="!newSkillForm.skill_name || !newSkillForm.skill_desc" class="btn-primary disabled:opacity-50 disabled:cursor-not-allowed">Next</button>
          </div>
        </div>
      </div>
    </Teleport>

    <!-- 第二步：编辑 Skill 内容弹窗 -->
    <Teleport to="body">
      <div v-if="isEditingContent" class="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4 modal-overlay">
        <div class="bg-dark-800 rounded-2xl w-full max-w-4xl border border-dark-600 shadow-2xl overflow-hidden modal-content" style="max-height: 90vh;">
          <div class="flex items-center justify-between p-5 border-b border-dark-600 bg-dark-700/50">
            <div class="flex items-center gap-3">
              <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-orange-500 to-red-500 flex items-center justify-center">
                <Wand2 class="w-5 h-5 text-white" />
              </div>
              <div>
                <h3 class="text-xl font-semibold text-white">Edit Skill Content</h3>
                <p class="text-sm text-gray-400">Configure skill details in SKILL.md format</p>
              </div>
            </div>
            <button @click="closeEditContent" class="btn-icon">
              <X class="w-5 h-5" />
            </button>
          </div>

          <div class="p-5" style="max-height: calc(90vh - 180px); overflow-y: auto;">
            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">SKILL.md Content</label>
              <textarea v-model="newSkillContent" rows="25" placeholder="Write your skill content in markdown format..." class="input-field resize-none font-mono text-sm" style="min-height: 500px;"></textarea>
            </div>

            <div class="mt-3 text-xs text-gray-500">
              <p>Tip: SKILL.md should contain YAML front matter with name and description, followed by the skill implementation in markdown.</p>
            </div>
          </div>

          <div class="flex items-center justify-between gap-3 p-5 border-t border-dark-600 bg-dark-700/50">
            <button @click="closeEditContent" class="btn-secondary">Back</button>
            <button @click="saveNewSkill" class="btn-primary">Create Skill</button>
          </div>
        </div>
      </div>
    </Teleport>

    <!-- 导入弹窗 -->
    <Teleport to="body">
      <div v-if="isImportingDialog" class="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4 modal-overlay">
        <div class="bg-dark-800 rounded-2xl w-full max-w-2xl border border-dark-600 shadow-2xl overflow-hidden modal-content" style="max-height: 90vh;">
          <!-- 第一步：选择文件 -->
          <div v-if="!isImportStep2">
            <div class="flex items-center justify-between p-5 border-b border-dark-600 bg-dark-700/50">
              <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-blue-500 to-indigo-500 flex items-center justify-center">
                  <FolderInput class="w-5 h-5 text-white" />
                </div>
                <div>
                  <h3 class="text-xl font-semibold text-white">Import Skill</h3>
                  <p class="text-sm text-gray-400">Select a file or folder to import</p>
                </div>
              </div>
              <button @click="closeImportDialog" class="btn-icon">
                <X class="w-5 h-5" />
              </button>
            </div>

            <div class="p-5 space-y-4">
              <!-- 导入文件选项 -->
              <div
                class="border-2 border-dashed border-dark-500 rounded-xl p-6 text-center cursor-pointer hover:border-blue-500 transition-colors"
                @click="fileInputRef?.click?.()"
              >
                <FolderInput class="w-10 h-10 mx-auto text-gray-400 mb-2" />
                <p class="text-white mb-1">Import File</p>
                <p class="text-sm text-gray-500">Select a single SKILL.md file</p>
              </div>
              <input
                ref="fileInputRef"
                type="file"
                accept=".md"
                style="display: none"
                @change="handleFileChange"
              />

              <!-- 导入文件夹选项 -->
              <input
                type="file"
                webkitdirectory=""
                directory=""
                multiple
                style="display: none"
                @change="handleFolderSelect"
                id="folderInput"
              />
              <label for="folderInput" class="block">
                <div
                  class="border-2 border-dashed border-dark-500 rounded-xl p-6 text-center cursor-pointer hover:border-green-500 transition-colors"
                >
                  <svg class="w-10 h-10 mx-auto text-gray-400 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"></path>
                  </svg>
                  <p class="text-white mb-1">Import Folder</p>
                  <p class="text-sm text-gray-500">Select a folder containing SKILL.md</p>
                </div>
              </label>
            </div>

            <div class="flex items-center justify-end gap-3 p-5 border-t border-dark-600 bg-dark-700/50">
              <button @click="closeImportDialog" class="btn-secondary">Cancel</button>
            </div>
          </template>

          <!-- 第二步：编辑内容 -->
          <template v-else>
            <div class="flex items-center justify-between p-5 border-b border-dark-600 bg-dark-700/50">
              <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-blue-500 to-indigo-500 flex items-center justify-center">
                  <FolderInput class="w-5 h-5 text-white" />
                </div>
                <div>
                  <h3 class="text-xl font-semibold text-white">Edit Skill Content</h3>
                  <p class="text-sm text-gray-400">Review and edit imported skill content</p>
                </div>
              </div>
              <button @click="closeImportDialog" class="btn-icon">
                <X class="w-5 h-5" />
              </button>
            </div>

            <div class="p-5 space-y-4" style="max-height: calc(90vh - 180px); overflow-y: auto;">
              <div>
                <label class="block text-sm font-medium text-gray-300 mb-2">Skill Name</label>
                <input v-model="importSkillName" type="text" class="input-field">
              </div>

              <div>
                <label class="block text-sm font-medium text-gray-300 mb-2">SKILL.md Content</label>
                <textarea v-model="importSkillContent" rows="20" class="input-field resize-none font-mono text-sm" style="min-height: 400px;"></textarea>
              </div>
            </div>

            <div class="flex items-center justify-between gap-3 p-5 border-t border-dark-600 bg-dark-700/50">
              <button @click="isImportStep2 = false" class="btn-secondary">Back</button>
              <button @click="submitImport" :disabled="isImporting" class="btn-primary disabled:opacity-50">
                {{ isImporting ? 'Importing...' : 'Import' }}
              </button>
            </div>
          </template>
        </div>
      </div>
    </Teleport>
  </div>
</template>

<style scoped>
/* 使用全局样式 */
</style>
