<script setup lang="ts">
import { Bot, Plus, Edit2, Trash2, Eye, EyeOff, Copy, Cpu, X, Search, SlidersHorizontal, PanelRightOpen } from 'lucide-vue-next'
import { useSkillsPage } from './composables/useSkillsPage'

const {
  AGENT_TYPES,
  AVAILABLE_TOOLS,
  VISIBILITY_OPTIONS,
  SOURCE_OPTIONS,
  STATUS_OPTIONS,
  BUILTIN_MCP_PACKS,
  skills,
  loading,
  saving,
  modalOpen,
  mcpPanelOpen,
  editingSkill,
  detailDrawerOpen,
  drawerTitleId,
  drawerDescriptionId,
  drawerPanelRef,
  searchQuery,
  selectedAgentFilter,
  selectedSourceFilter,
  selectedStatusFilter,
  selectedVisibilityFilter,
  mcpPacksByAgent,
  activeSkillCount,
  coverageToolCount,
  activeRatio,
  selectedSkill,
  filteredSkills,
  form,
  openCreateModal,
  openEditModal,
  closeModal,
  openMcpPanel,
  closeMcpPanel,
  selectSkill,
  closeDetailDrawer,
  handleDrawerKeydown,
  formatRelativeTime,
  getBindingCount,
  getSourceLabel,
  getStatusLabel,
  getToolPreview,
  getToolOverflow,
  createSkill,
  updateSkill,
  deleteSkill,
  toggleActive,
  copySkill,
  toggleTool,
  animateIn,
  animateOut,
} = useSkillsPage()
</script>

<template>
  <div class="skill-view scanlines">
    <div class="bg-grid"></div>
    <div class="bg-glow"></div>
    <div class="bg-scan"></div>
    <div class="bg-orbit"></div>
    <div class="bg-particles"></div>

    <div class="view-header">
      <div class="header-copy">
        <div class="header-title" data-testid="skills-page-title">
          <span class="title-bracket">[</span>
          <span class="title-text">能力中心</span>
          <span class="title-bracket">]</span>
        </div>
        <p class="header-subtitle">Skill Registry / Runtime Capabilities</p>
      </div>
      <div class="header-actions">
        <button class="btn-mcp" data-testid="skills-mcp-button" @click="openMcpPanel">
          <Cpu :size="14" />
          <span>MCP</span>
        </button>
        <button class="btn-add" data-testid="skills-create-button" @click="openCreateModal">
          <Plus :size="14" />
          <span>新建技能</span>
        </button>
      </div>
    </div>

    <div class="metrics-strip" data-testid="skills-metrics-strip">
      <div class="metric-panel">
        <span class="metric-label">TOTAL</span>
        <strong class="metric-value">{{ skills.length }}</strong>
      </div>
      <div class="metric-panel">
        <span class="metric-label">ACTIVE</span>
        <strong class="metric-value">{{ activeSkillCount }}</strong>
      </div>
      <div class="metric-panel">
        <span class="metric-label">UPTIME</span>
        <strong class="metric-value">{{ activeRatio }}</strong>
      </div>
      <div class="metric-panel">
        <span class="metric-label">TOOLS</span>
        <strong class="metric-value">{{ coverageToolCount }}</strong>
      </div>
      <div class="metric-panel">
        <span class="metric-label">PACKS</span>
        <strong class="metric-value">{{ BUILTIN_MCP_PACKS.length }}</strong>
      </div>
    </div>

    <div class="toolbar" data-testid="skills-filter-bar">
      <label class="search-box" for="skills-search-input">
        <Search :size="14" />
        <span class="sr-only">搜索技能</span>
        <input id="skills-search-input" v-model="searchQuery" type="text" placeholder="鎼滅储鎶€鑳姐€佸伐鍏锋垨绫诲瀷" data-testid="skills-search-input" />
      </label>
      <div class="filter-group">
        <span class="filter-label"><SlidersHorizontal :size="12" /> FILTER</span>
        <label class="sr-only" for="skills-agent-filter">按类型筛选</label>
        <select id="skills-agent-filter" v-model="selectedAgentFilter" class="filter-select" data-testid="skills-agent-filter">
          <option value="all">鍏ㄩ儴绫诲瀷</option>
          <option v-for="type in AGENT_TYPES" :key="type" :value="type">{{ type }}</option>
        </select>
        <label class="sr-only" for="skills-source-filter">按来源筛选</label>
        <select id="skills-source-filter" v-model="selectedSourceFilter" class="filter-select" data-testid="skills-source-filter">
          <option v-for="source in SOURCE_OPTIONS" :key="source" :value="source">{{ source }}</option>
        </select>
        <label class="sr-only" for="skills-status-filter">按状态筛选</label>
        <select id="skills-status-filter" v-model="selectedStatusFilter" class="filter-select" data-testid="skills-status-filter">
          <option v-for="status in STATUS_OPTIONS" :key="status" :value="status">{{ status }}</option>
        </select>
        <label class="sr-only" for="skills-visibility-filter">按可见性筛选</label>
        <select id="skills-visibility-filter" v-model="selectedVisibilityFilter" class="filter-select" data-testid="skills-visibility-filter">
          <option value="all">all visibility</option>
          <option v-for="visibility in VISIBILITY_OPTIONS" :key="visibility" :value="visibility">{{ visibility }}</option>
        </select>
      </div>
    </div>

    <div v-if="loading" class="loading-shell" data-testid="skills-loading-state">
      <div class="table-shell">
        <div class="table-shell-head"></div>
        <div v-for="row in 6" :key="row" class="table-shell-row"></div>
      </div>
    </div>

    <div v-else-if="filteredSkills.length > 0" class="console-layout">
      <section class="table-panel holo-card" aria-label="鎶€鑳借〃鏍?">
        <div class="table-viewport">
          <div class="skills-table-wrap" data-testid="skills-table-wrap">
            <table class="skills-table" data-testid="skills-table">
            <thead>
              <tr>
                <th>Skill</th>
                <th>Type</th>
                <th>Tools</th>
                <th>Visibility</th>
                <th>Source</th>
                <th>Status</th>
                <th>Bindings</th>
                <th>Updated</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="skill in filteredSkills"
                :key="skill.id"
                class="table-row"
                :class="{ selected: selectedSkill?.id === skill.id, inactive: !skill.is_active }"
                :data-testid="`skills-table-row-${skill.id}`"
                :aria-selected="selectedSkill?.id === skill.id ? 'true' : 'false'"
                @click="selectSkill(skill.id, $event.currentTarget)"
              >
                <td>
                  <button
                    class="skill-row-trigger"
                    type="button"
                    :aria-label="`鏌ョ湅 ${skill.name}`"
                    @click.stop="selectSkill(skill.id, $event.currentTarget)"
                  >
                    <div class="skill-cell-main">
                      <div class="skill-title-row">
                        <Bot :size="14" class="skill-icon" />
                        <span class="skill-name">{{ skill.name }}</span>
                        <span v-if="skill.is_builtin" class="inline-badge builtin-badge" data-testid="builtin-skill-badge">内置</span>
                      </div>
                      <div class="skill-description">{{ skill.description || '鏆傛棤鎻忚堪' }}</div>
                    </div>
                  </button>
                </td>
                <td><span class="mono-pill">{{ skill.agent_type }}</span></td>
                <td>
                  <div class="tool-list compact">
                    <span v-for="tool in getToolPreview(skill)" :key="tool" class="tool-tag">{{ tool }}</span>
                    <span v-if="getToolOverflow(skill) > 0" class="tool-tag ghost">+{{ getToolOverflow(skill) }}</span>
                  </div>
                </td>
                <td><span class="visibility-badge" :class="skill.visibility">{{ skill.visibility }}</span></td>
                <td><span class="source-badge" :class="skill.is_builtin ? 'builtin' : 'custom'">{{ getSourceLabel(skill) }}</span></td>
                <td>
                  <span class="status-pill" :class="skill.is_active ? 'active' : 'inactive'">
                    <span class="status-dot"></span>
                    {{ getStatusLabel(skill) }}
                  </span>
                </td>
                <td class="numeric-cell">{{ getBindingCount(skill) }}</td>
                <td class="updated-cell">{{ formatRelativeTime(skill.updated_at) }}</td>
                <td>
                  <div class="skill-actions" @click.stop>
                    <button
                      class="action-btn"
                      :class="{ active: skill.is_active }"
                      @click="toggleActive(skill)"
                      :title="skill.is_active ? 'Disable' : 'Enable'"
                      :aria-label="skill.is_active ? `鍋滅敤 ${skill.name}` : `鍚敤 ${skill.name}`"
                    >
                      <Eye v-if="skill.is_active" :size="14" />
                      <EyeOff v-else :size="14" />
                    </button>
                    <button class="action-btn" @click="copySkill(skill)" title="Copy" :aria-label="`澶嶅埗 ${skill.name}`">
                      <Copy :size="14" />
                    </button>
                    <button class="action-btn edit" @click="openEditModal(skill)" title="Edit" :aria-label="`缂栬緫 ${skill.name}`">
                      <Edit2 :size="14" />
                    </button>
                    <button class="action-btn delete" @click="deleteSkill(skill)" title="Delete" :aria-label="`鍒犻櫎 ${skill.name}`">
                      <Trash2 :size="14" />
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </section>
  </div>

    <Transition :css="false" @enter="animateIn" @leave="animateOut">
      <div
        v-if="detailDrawerOpen && selectedSkill"
        class="drawer-overlay"
        data-testid="skills-detail-drawer-overlay"
        @click.self="closeDetailDrawer"
      >
        <aside
          ref="drawerPanelRef"
          class="detail-drawer holo-card"
          data-testid="skills-detail-panel"
          role="dialog"
          aria-modal="true"
          :aria-labelledby="drawerTitleId"
          :aria-describedby="drawerDescriptionId"
          tabindex="-1"
          @keydown="handleDrawerKeydown"
        >
          <div class="panel-header detail-header">
            <div>
              <p class="panel-kicker">DETAIL STREAM</p>
              <h2 :id="drawerTitleId" class="panel-title">{{ selectedSkill.name }}</h2>
            </div>
            <div class="detail-header-actions">
              <button class="detail-action" @click="openEditModal(selectedSkill)">
                <PanelRightOpen :size="14" />
                <span>缂栬緫</span>
              </button>
              <button class="btn-close" aria-label="关闭详情滑窗" @click="closeDetailDrawer"><X :size="16" /></button>
            </div>
          </div>

          <div class="detail-section">
            <span class="detail-label">DESCRIPTION</span>
            <p :id="drawerDescriptionId" class="detail-copy">{{ selectedSkill.description || '鏆傛棤鎻忚堪' }}</p>
          </div>

          <div class="detail-grid">
            <div class="detail-stat">
              <span class="detail-label">TYPE</span>
              <strong>{{ selectedSkill.agent_type }}</strong>
            </div>
            <div class="detail-stat">
              <span class="detail-label">STATUS</span>
              <strong>{{ getStatusLabel(selectedSkill) }}</strong>
            </div>
            <div class="detail-stat">
              <span class="detail-label">SOURCE</span>
              <strong>{{ getSourceLabel(selectedSkill) }}</strong>
            </div>
            <div class="detail-stat">
              <span class="detail-label">UPDATED</span>
              <strong>{{ formatRelativeTime(selectedSkill.updated_at) }}</strong>
            </div>
          </div>

          <div class="detail-section">
            <span class="detail-label">TOOLS</span>
            <div class="tool-list">
              <span v-for="tool in selectedSkill.tools" :key="tool" class="tool-tag">{{ tool }}</span>
            </div>
          </div>

          <div class="detail-section">
            <span class="detail-label">INSTRUCTIONS</span>
            <pre class="detail-code">{{ selectedSkill.instructions }}</pre>
          </div>
        </aside>
      </div>
    </Transition>

    <div v-if="!loading && filteredSkills.length === 0" class="empty-state">
      <Bot :size="48" class="empty-icon" />
      <p class="empty-text">No skills found</p>
      <button class="btn-add" @click="openCreateModal">
        <Plus :size="14" />
        <span>Create your first skill</span>
      </button>
    </div>

    <Transition :css="false" @enter="animateIn" @leave="animateOut">
      <div v-if="mcpPanelOpen" class="modal-overlay" @click.self="closeMcpPanel">
        <div class="modal-card mcp-panel" data-testid="skills-mcp-panel">
          <div class="modal-header">
            <span class="modal-title">// MCP 工具能力包</span>
            <button class="btn-close" aria-label="关闭 MCP 面板" @click="closeMcpPanel"><X :size="16" /></button>
          </div>
          <div class="modal-body">
            <div class="mcp-summary">
              <p class="mcp-summary-title">内置能力总览</p>
              <p class="mcp-summary-text">本轮 MCP 先定义为能力中心内部可绑定的工具能力包，不单独跳转页面。</p>
            </div>
            <section v-for="(packs, agentType) in mcpPacksByAgent" :key="agentType" class="mcp-section">
              <div class="mcp-section-head">
                <span class="mcp-section-title">{{ agentType }}</span>
                <span class="mcp-section-count">{{ packs.length }} 组</span>
              </div>
              <div class="mcp-table-wrap">
                <table class="mcp-table">
                  <thead>
                    <tr>
                      <th>Pack</th>
                      <th>Category</th>
                      <th>Tools</th>
                      <th>Description</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="pack in packs" :key="pack.id">
                      <td class="mcp-pack-name">{{ pack.name }}</td>
                      <td><span class="mono-pill">{{ pack.category }}</span></td>
                      <td>
                        <div class="tool-list compact">
                          <span v-for="tool in pack.tools" :key="tool" class="tool-tag">{{ tool }}</span>
                        </div>
                      </td>
                      <td class="mcp-description">{{ pack.description }}</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </section>
          </div>
        </div>
      </div>
    </Transition>

    <Transition :css="false" @enter="animateIn" @leave="animateOut">
      <div v-if="modalOpen" class="modal-overlay" @click.self="closeModal">
        <div class="modal-card" data-testid="skills-skill-modal">
          <div class="modal-header">
            <span class="modal-title">{{ editingSkill ? '// 编辑技能' : '// 新建技能' }}</span>
            <button class="btn-close" aria-label="关闭技能弹窗" @click="closeModal"><X :size="16" /></button>
          </div>
          <div class="modal-body">
            <div class="form-group">
              <label class="form-label" for="skill-name-input">// NAME</label>
              <input id="skill-name-input" v-model="form.name" data-testid="skill-name-input" type="text" class="form-input" placeholder="Skill name" />
            </div>

            <div class="form-group">
              <label class="form-label" for="skill-description-input">// DESCRIPTION</label>
              <textarea id="skill-description-input" v-model="form.description" class="form-textarea" rows="2" placeholder="Describe what this skill does..."></textarea>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label class="form-label" for="skill-agent-type-select">// AGENT TYPE</label>
                <select id="skill-agent-type-select" v-model="form.agent_type" data-testid="skill-agent-type-select" class="form-select">
                  <option v-for="type in AGENT_TYPES" :key="type" :value="type">{{ type }}</option>
                </select>
              </div>

              <div class="form-group">
                <label class="form-label" for="skill-visibility-select">// VISIBILITY</label>
                <select id="skill-visibility-select" v-model="form.visibility" class="form-select">
                  <option v-for="vis in VISIBILITY_OPTIONS" :key="vis" :value="vis">{{ vis }}</option>
                </select>
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">// TOOLS</label>
              <div class="tools-grid">
                <label v-for="tool in AVAILABLE_TOOLS" :key="tool" class="tool-checkbox">
                  <input type="checkbox" :checked="form.tools?.includes(tool)" @change="toggleTool(tool)" />
                  <span class="checkbox-custom"></span>
                  <span>{{ tool }}</span>
                </label>
              </div>
            </div>

            <div class="form-group flex-1">
              <label class="form-label" for="skill-instructions-input">// INSTRUCTIONS</label>
              <textarea id="skill-instructions-input" v-model="form.instructions" data-testid="skill-instructions-input" class="form-textarea code-textarea" rows="8" placeholder="Enter skill instructions..."></textarea>
            </div>
          </div>
          <div class="modal-footer">
            <button class="btn-secondary" @click="closeModal">Cancel</button>
            <button
              class="btn-primary"
              data-testid="skill-save-button"
              @click="editingSkill ? updateSkill() : createSkill()"
              :disabled="saving || !form.name || !form.instructions"
            >
              <span v-if="saving" class="btn-loader"></span>
              {{ saving ? 'Saving...' : (editingSkill ? 'Update' : 'Create') }}
            </button>
          </div>
        </div>
      </div>
    </Transition>
  </div>
</template>

<style scoped src="./skillsPage.css"></style>


