<script setup lang="ts">
import { ref, onMounted } from 'vue'

function animateIn(el: Element, done: () => void) {
  const target = el as HTMLElement
  target.animate(
    [
      { opacity: '0', transform: 'translateY(12px)' },
      { opacity: '1', transform: 'translateY(0)' },
    ],
    { duration: 220, easing: 'ease-out', fill: 'forwards' },
  ).finished.finally(done)
}

function animateOut(el: Element, done: () => void) {
  const target = el as HTMLElement
  target.animate(
    [
      { opacity: '1', transform: 'translateY(0)' },
      { opacity: '0', transform: 'translateY(12px)' },
    ],
    { duration: 180, easing: 'ease-in', fill: 'forwards' },
  ).finished.finally(done)
}
import { skillApi, type Skill, type SkillCreate } from '@/api/skill'
import { Bot, Plus, Edit2, Trash2, Eye, EyeOff, Copy, X } from 'lucide-vue-next'

// Available agent types and tools
const AGENT_TYPES = ['general', 'coder', 'analyst', 'planner', 'executor', 'librarian']
const AVAILABLE_TOOLS = ['file_operations', 'web_search', 'code_execution', 'database', 'api_calls', 'shell', 'git']
const VISIBILITY_OPTIONS = ['private', 'team', 'market'] as const

// State
const skills = ref<Skill[]>([])
const loading = ref(false)
const saving = ref(false)
const modalOpen = ref(false)
const editingSkill = ref<Skill | null>(null)

// Form state
const form = ref<SkillCreate>({
  name: '',
  description: '',
  instructions: '',
  agent_type: 'general',
  tools: [],
  visibility: 'private',
  is_active: true,
})

// Reset form
function resetForm() {
  form.value = {
    name: '',
    description: '',
    instructions: '',
    agent_type: 'general',
    tools: [],
    visibility: 'private',
    is_active: true,
  }
}

// Open create modal
function openCreateModal() {
  editingSkill.value = null
  resetForm()
  modalOpen.value = true
}

// Open edit modal
function openEditModal(skill: Skill) {
  editingSkill.value = skill
  form.value = {
    name: skill.name,
    description: skill.description || '',
    instructions: skill.instructions,
    agent_type: skill.agent_type,
    tools: [...skill.tools],
    visibility: skill.visibility,
    is_active: skill.is_active,
  }
  modalOpen.value = true
}

// Close modal
function closeModal() {
  modalOpen.value = false
  editingSkill.value = null
  resetForm()
}

// Fetch skills
async function fetchSkills() {
  loading.value = true
  try {
    const res = await skillApi.list()
    skills.value = res.data
  } catch (e) {
    console.error('Failed to fetch skills', e)
  } finally {
    loading.value = false
  }
}

// Create skill
async function createSkill() {
  saving.value = true
  try {
    const res = await skillApi.create(form.value)
    skills.value.push(res.data)
    closeModal()
  } catch (e) {
    console.error('Failed to create skill', e)
  } finally {
    saving.value = false
  }
}

// Update skill
async function updateSkill() {
  if (!editingSkill.value) return
  saving.value = true
  try {
    const res = await skillApi.update(editingSkill.value.id, form.value)
    const idx = skills.value.findIndex(s => s.id === editingSkill.value!.id)
    if (idx !== -1) {
      skills.value[idx] = res.data
    }
    closeModal()
  } catch (e) {
    console.error('Failed to update skill', e)
  } finally {
    saving.value = false
  }
}

// Delete skill
async function deleteSkill(skill: Skill) {
  if (!confirm(`Delete skill "${skill.name}"?`)) return
  try {
    await skillApi.delete(skill.id)
    skills.value = skills.value.filter(s => s.id !== skill.id)
  } catch (e) {
    console.error('Failed to delete skill', e)
  }
}

// Toggle active
async function toggleActive(skill: Skill) {
  try {
    const res = await skillApi.update(skill.id, { is_active: !skill.is_active })
    const idx = skills.value.findIndex(s => s.id === skill.id)
    if (idx !== -1) {
      skills.value[idx] = res.data
    }
  } catch (e) {
    console.error('Failed to toggle skill active state', e)
  }
}

// Copy skill to clipboard
function copySkill(skill: Skill) {
  const skillText = JSON.stringify({
    name: skill.name,
    description: skill.description,
    instructions: skill.instructions,
    agent_type: skill.agent_type,
    tools: skill.tools,
    visibility: skill.visibility,
  }, null, 2)
  navigator.clipboard.writeText(skillText).then(() => {
    // Could add toast notification here
  }).catch(e => {
    console.error('Failed to copy skill', e)
  })
}

// Toggle tool selection
function toggleTool(tool: string) {
  const idx = form.value.tools?.indexOf(tool) ?? -1
  if (idx === -1) {
    form.value.tools = [...(form.value.tools || []), tool]
  } else {
    form.value.tools = form.value.tools?.filter(t => t !== tool) ?? []
  }
}

onMounted(fetchSkills)
</script>

<template>
  <div class="skill-view scanlines">
    <!-- Background -->
    <div class="bg-grid"></div>
    <div class="bg-glow"></div>

    <!-- Header -->
    <div class="view-header">
      <div class="header-title">
        <span class="title-bracket">[</span>
        <span class="title-text">技能中心</span>
        <span class="title-bracket">]</span>
      </div>
      <div class="header-actions">
        <button class="btn-icon" @click="fetchSkills" :class="{ spinning: loading }" title="Refresh">
          <Copy :size="14" />
        </button>
        <button class="btn-add" @click="openCreateModal">
          <Plus :size="14" />
          <span>新建技能</span>
        </button>
      </div>
    </div>

    <!-- Loading -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-text">LOADING...</div>
    </div>

    <!-- Skills List -->
    <div v-else-if="skills.length > 0" class="skills-grid">
      <div
        v-for="skill in skills"
        :key="skill.id"
        class="skill-card holo-card"
        :class="{ inactive: !skill.is_active }"
      >
        <div class="skill-header">
          <div class="skill-title">
            <Bot :size="14" class="skill-icon" />
            <span class="skill-name">{{ skill.name }}</span>
          </div>
          <span class="badge agent-badge">{{ skill.agent_type }}</span>
        </div>

        <p class="skill-description">{{ skill.description || 'No description' }}</p>

        <div v-if="skill.tools && skill.tools.length > 0" class="skill-tools">
          <span v-for="tool in skill.tools" :key="tool" class="tool-tag">{{ tool }}</span>
        </div>

        <div class="skill-footer">
          <div class="skill-meta">
            <span class="visibility-badge" :class="skill.visibility">{{ skill.visibility }}</span>
          </div>
          <div class="skill-actions">
            <button
              class="action-btn"
              :class="{ active: skill.is_active }"
              @click="toggleActive(skill)"
              :title="skill.is_active ? 'Disable' : 'Enable'"
            >
              <Eye v-if="skill.is_active" :size="14" />
              <EyeOff v-else :size="14" />
            </button>
            <button class="action-btn" @click="copySkill(skill)" title="Copy">
              <Copy :size="14" />
            </button>
            <button class="action-btn edit" @click="openEditModal(skill)" title="Edit">
              <Edit2 :size="14" />
            </button>
            <button class="action-btn delete" @click="deleteSkill(skill)" title="Delete">
              <Trash2 :size="14" />
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- Empty State -->
    <div v-else 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>

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

            <div class="form-group">
              <label class="form-label">// DESCRIPTION</label>
              <textarea 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">// AGENT TYPE</label>
                <select v-model="form.agent_type" 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">// VISIBILITY</label>
                <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">// INSTRUCTIONS</label>
              <textarea v-model="form.instructions" 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"
              @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>
.skill-view {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--bg-void);
  position: relative;
  overflow: hidden;
}

.bg-grid {
  position: absolute;
  inset: 0;
  background-image:
    linear-gradient(rgba(0,245,212,0.04) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0,245,212,0.04) 1px, transparent 1px);
  background-size: 40px 40px;
  pointer-events: none;
  z-index: 0;
}

.bg-glow {
  position: absolute;
  inset: 0;
  background: radial-gradient(ellipse 80% 60% at 50% 40%, rgba(0,245,212,0.05) 0%, transparent 70%);
  pointer-events: none;
  z-index: 0;
}

/* Header */
.view-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 24px;
  border-bottom: 1px solid var(--border-dim);
  background: rgba(5,8,16,0.6);
  backdrop-filter: blur(8px);
  position: relative;
  z-index: 10;
}

.header-title {
  font-family: var(--font-display);
  font-size: 13px;
  letter-spacing: 0.2em;
  color: var(--text-primary);
}

.title-bracket {
  color: var(--accent-cyan);
  opacity: 0.6;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.btn-icon {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--bg-card);
  border: 1px solid var(--border-mid);
  border-radius: var(--radius-sm);
  color: var(--text-secondary);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.btn-icon:hover {
  border-color: var(--accent-cyan);
  color: var(--accent-cyan);
  box-shadow: var(--glow-cyan);
}

.btn-icon.spinning svg {
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.btn-add {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 14px;
  background: rgba(0,245,212,0.08);
  border: 1px solid rgba(0,245,212,0.3);
  border-radius: var(--radius-sm);
  color: var(--accent-cyan);
  font-family: var(--font-mono);
  font-size: 11px;
  letter-spacing: 0.1em;
  cursor: pointer;
  transition: all var(--transition-fast);
}

.btn-add:hover {
  background: rgba(0,245,212,0.15);
  border-color: var(--accent-cyan);
  box-shadow: var(--glow-cyan);
}

/* Loading */
.loading-overlay {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(5,8,16,0.8);
  z-index: 50;
}

.loading-text {
  font-family: var(--font-mono);
  font-size: 12px;
  letter-spacing: 0.2em;
  color: var(--accent-cyan);
  animation: pulse 1s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 0.4; }
  50% { opacity: 1; }
}

/* Skills Grid */
.skills-grid {
  flex: 1;
  overflow-y: auto;
  padding: 20px 24px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
  gap: 16px;
  position: relative;
  z-index: 1;
}

.skills-grid::-webkit-scrollbar {
  width: 4px;
}

.skills-grid::-webkit-scrollbar-thumb {
  background: var(--border-mid);
  border-radius: 2px;
}

/* Skill Card */
.skill-card {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.skill-card.inactive {
  opacity: 0.5;
}

.skill-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.skill-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.skill-icon {
  color: var(--accent-cyan);
}

.skill-name {
  font-family: var(--font-display);
  font-size: 14px;
  font-weight: 600;
  color: var(--text-primary);
  letter-spacing: 0.05em;
}

.agent-badge {
  background: var(--accent-cyan-dim);
  color: var(--accent-cyan);
  border: 1px solid rgba(0,245,212,0.2);
}

.skill-description {
  font-family: var(--font-mono);
  font-size: 11px;
  color: var(--text-secondary);
  line-height: 1.5;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  text-overflow: ellipsis;
}

.skill-tools {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.tool-tag {
  padding: 2px 8px;
  background: var(--accent-purple-dim);
  color: var(--accent-purple);
  border: 1px solid rgba(123,44,191,0.2);
  border-radius: 3px;
  font-family: var(--font-mono);
  font-size: 9px;
  letter-spacing: 0.05em;
}

.skill-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 8px;
  border-top: 1px solid var(--border-dim);
}

.skill-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.visibility-badge {
  font-family: var(--font-mono);
  font-size: 9px;
  letter-spacing: 0.1em;
  text-transform: uppercase;
  padding: 2px 6px;
  border-radius: 3px;
}

.visibility-badge.private {
  background: rgba(255,71,87,0.1);
  color: var(--accent-red);
  border: 1px solid rgba(255,71,87,0.2);
}

.visibility-badge.team {
  background: rgba(249,168,37,0.1);
  color: var(--accent-amber);
  border: 1px solid rgba(249,168,37,0.2);
}

.visibility-badge.market {
  background: rgba(0,230,118,0.1);
  color: var(--accent-green);
  border: 1px solid rgba(0,230,118,0.2);
}

.skill-actions {
  display: flex;
  gap: 4px;
}

.action-btn {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: transparent;
  border: 1px solid var(--border-dim);
  border-radius: var(--radius-sm);
  color: var(--text-dim);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.action-btn:hover {
  border-color: var(--accent-cyan);
  color: var(--accent-cyan);
}

.action-btn.active {
  color: var(--accent-cyan);
}

.action-btn.edit:hover {
  border-color: var(--accent-amber);
  color: var(--accent-amber);
}

.action-btn.delete:hover {
  border-color: var(--accent-red);
  color: var(--accent-red);
}

/* Empty State */
.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
  position: relative;
  z-index: 1;
}

.empty-icon {
  color: var(--text-dim);
  opacity: 0.5;
}

.empty-text {
  font-family: var(--font-mono);
  font-size: 12px;
  color: var(--text-dim);
  letter-spacing: 0.1em;
}

/* Modal */
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0,0,0,.7);
  backdrop-filter: blur(4px);
  z-index: 200;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-card {
  width: 520px;
  max-height: 85vh;
  background: rgba(10,15,26,.98);
  border: 1px solid var(--border-mid);
  border-radius: var(--radius-lg);
  display: flex;
  flex-direction: column;
  box-shadow: 0 20px 60px rgba(0,0,0,.6), 0 0 0 1px rgba(0,245,212,.05);
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid var(--border-dim);
}

.modal-title {
  font-family: var(--font-display);
  font-size: 11px;
  letter-spacing: 0.15em;
  color: var(--accent-cyan);
}

.btn-close {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: transparent;
  border: 1px solid var(--border-dim);
  border-radius: var(--radius-sm);
  color: var(--text-dim);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.btn-close:hover {
  border-color: var(--accent-red);
  color: var(--accent-red);
}

.modal-body {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.modal-body::-webkit-scrollbar {
  width: 4px;
}

.modal-body::-webkit-scrollbar-thumb {
  background: var(--border-mid);
  border-radius: 2px;
}

.modal-footer {
  display: flex;
  gap: 12px;
  padding: 16px 20px;
  border-top: 1px solid var(--border-dim);
}

/* Form */
.form-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-group.flex-1 {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.form-row {
  display: flex;
  gap: 14px;
}

.form-row .form-group {
  flex: 1;
}

.form-label {
  font-family: var(--font-mono);
  font-size: 9px;
  letter-spacing: 0.15em;
  color: var(--text-dim);
}

.form-input,
.form-textarea,
.form-select {
  background: var(--bg-card);
  border: 1px solid var(--border-mid);
  border-radius: var(--radius-sm);
  padding: 10px 12px;
  color: var(--text-primary);
  font-family: var(--font-mono);
  font-size: 12px;
  outline: none;
  transition: border-color var(--transition-fast);
}

.form-input:focus,
.form-textarea:focus,
.form-select:focus {
  border-color: var(--accent-cyan);
  box-shadow: 0 0 0 1px rgba(0,245,212,.1);
}

.form-textarea {
  resize: none;
  line-height: 1.5;
}

.code-textarea {
  font-size: 11px;
  flex: 1;
}

.form-select {
  cursor: pointer;
}

/* Tools Grid */
.tools-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
}

.tool-checkbox {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  font-family: var(--font-mono);
  font-size: 10px;
  color: var(--text-secondary);
}

.tool-checkbox input {
  display: none;
}

.tool-checkbox .checkbox-custom {
  width: 14px;
  height: 14px;
  border: 1px solid var(--border-mid);
  border-radius: 3px;
  background: var(--bg-card);
  position: relative;
  flex-shrink: 0;
}

.tool-checkbox input:checked + .checkbox-custom {
  background: var(--accent-cyan);
  border-color: var(--accent-cyan);
}

.tool-checkbox input:checked + .checkbox-custom::after {
  content: '\2713';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: var(--bg-void);
  font-size: 10px;
}

/* Buttons */
.btn-secondary,
.btn-primary {
  flex: 1;
  padding: 10px 16px;
  border-radius: var(--radius-sm);
  font-family: var(--font-mono);
  font-size: 11px;
  letter-spacing: 0.1em;
  cursor: pointer;
  transition: all var(--transition-fast);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.btn-secondary {
  background: transparent;
  border: 1px solid var(--border-mid);
  color: var(--text-secondary);
}

.btn-secondary:hover {
  border-color: var(--accent-cyan);
  color: var(--accent-cyan);
}

.btn-primary {
  background: rgba(0,245,212,.1);
  border: 1px solid var(--accent-cyan);
  color: var(--accent-cyan);
}

.btn-primary:hover:not(:disabled) {
  background: rgba(0,245,212,.2);
  box-shadow: var(--glow-cyan);
}

.btn-primary:disabled {
  opacity: 0.4;
  cursor: not-allowed;
}

.btn-loader {
  width: 12px;
  height: 12px;
  border: 1.5px solid transparent;
  border-top-color: var(--accent-cyan);
  border-radius: 50%;
  animation: spin .6s linear infinite;
}

/* Animation helpers */
@keyframes animateIn {
  from { opacity: 0; transform: scale(0.95); }
  to { opacity: 1; transform: scale(1); }
}

@keyframes animateOut {
  from { opacity: 1; transform: scale(1); }
  to { opacity: 0; transform: scale(0.95); }
}
</style>
