<template>
  <div class="skills-view">
    <div class="skills-view__header">
      <a-select
        v-model:value="selectedCapability"
        placeholder="按能力标签筛选"
        allow-clear
        style="width: 200px"
        @change="handleCapabilityChange"
      >
        <a-select-option v-for="cap in skillsStore.capabilities" :key="cap.name" :value="cap.name">
          {{ cap.display_name }} ({{ cap.skill_count }})
        </a-select-option>
      </a-select>
      <a-space>
        <a-button type="primary" @click="showInstallModal = true">
          <template #icon><PlusOutlined /></template>
          安装技能
        </a-button>
        <a-button @click="handleRefresh" :loading="skillsStore.isLoading">
          <template #icon><ReloadOutlined /></template>
          刷新
        </a-button>
      </a-space>
    </div>

    <a-spin :spinning="skillsStore.isLoading">
      <!-- 通用执行引擎模板 -->
      <section v-if="skillsStore.agentTemplates.length > 0" class="skills-view__group">
        <div class="skills-view__group-header">
          <ThunderboltOutlined class="skills-view__group-icon" />
          <span class="skills-view__group-title">执行引擎</span>
          <a-tag color="purple">{{ skillsStore.agentTemplates.length }}</a-tag>
          <span class="skills-view__group-hint">通用推理模式，决定 Agent 如何思考和调用工具</span>
        </div>
        <div class="skills-view__grid">
          <SkillCard
            v-for="skill in skillsStore.agentTemplates"
            :key="skill.name"
            :skill="skill"
            @click="handleSkillClick(skill.name)"
          />
        </div>
      </section>

      <!-- 业务领域技能 -->
      <section v-if="skillsStore.businessSkills.length > 0" class="skills-view__group">
        <div class="skills-view__group-header">
          <AppstoreOutlined class="skills-view__group-icon" />
          <span class="skills-view__group-title">业务技能</span>
          <a-tag color="blue">{{ skillsStore.businessSkills.length }}</a-tag>
          <span class="skills-view__group-hint">面向具体业务场景的领域能力</span>
        </div>
        <div class="skills-view__grid">
          <SkillCard
            v-for="skill in skillsStore.businessSkills"
            :key="skill.name"
            :skill="skill"
            @click="handleSkillClick(skill.name)"
          />
        </div>
      </section>

      <a-empty
        v-if="!skillsStore.isLoading && skillsStore.agentTemplates.length + skillsStore.businessSkills.length === 0"
        description="暂无已注册技能"
      />
    </a-spin>

    <SkillDetail
      :visible="showDetail"
      :skill="skillsStore.selectedSkill"
      @close="handleDetailClose"
    />

    <a-modal
      v-model:open="showInstallModal"
      title="安装技能"
      :confirm-loading="installing"
      @ok="handleInstall"
      ok-text="安装"
      cancel-text="取消"
    >
      <a-form layout="vertical">
        <a-form-item label="技能名称" required>
          <a-input v-model:value="installName" placeholder="例如: find-skills" />
        </a-form-item>
        <a-form-item label="来源 URL（可选）">
          <a-input v-model:value="installSource" placeholder="https://... 或留空自动搜索" />
        </a-form-item>
      </a-form>
      <a-alert v-if="installError" :message="installError" type="error" show-icon style="margin-top: 8px" />
      <a-alert v-if="installSuccess" :message="`技能 ${installSuccess} 安装成功！`" type="success" show-icon style="margin-top: 8px" />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ReloadOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { useSkillsStore } from '@/stores/skills'
import { skillsApi } from '@/api/skills'
import SkillCard from '@/components/skills/SkillCard.vue'
import SkillDetail from '@/components/skills/SkillDetail.vue'

const skillsStore = useSkillsStore()
const selectedCapability = ref<string | undefined>(undefined)
const showDetail = ref(false)

// Install state
const showInstallModal = ref(false)
const installName = ref('')
const installSource = ref('')
const installing = ref(false)
const installError = ref('')
const installSuccess = ref('')

onMounted(async () => {
  await Promise.all([
    skillsStore.fetchSkills(),
    skillsStore.fetchCapabilities(),
  ])
})

async function handleCapabilityChange(value: string | undefined): Promise<void> {
  skillsStore.setCapabilityFilter(value ?? null)
  await skillsStore.fetchSkills()
}

async function handleRefresh(): Promise<void> {
  await Promise.all([
    skillsStore.fetchSkills(),
    skillsStore.fetchCapabilities(),
  ])
}

async function handleSkillClick(skillName: string): Promise<void> {
  await skillsStore.fetchSkillDetail(skillName)
  showDetail.value = true
}

function handleDetailClose(): void {
  showDetail.value = false
  skillsStore.clearSelectedSkill()
}

async function handleInstall(): Promise<void> {
  if (!installName.value.trim()) {
    installError.value = '请输入技能名称'
    return
  }
  installing.value = true
  installError.value = ''
  installSuccess.value = ''
  try {
    const result = await skillsApi.installSkill(
      installName.value.trim(),
      installSource.value.trim() || undefined
    )
    installSuccess.value = result.name
    message.success(`技能 ${result.name} 安装成功！`)
    // Refresh skill list
    await handleRefresh()
  } catch (e: any) {
    installError.value = e?.message || '安装失败'
  } finally {
    installing.value = false
  }
}
</script>

<style scoped>
.skills-view {
  height: 100%;
  padding: var(--space-5) var(--space-6);
  overflow-y: auto;
  background: var(--bg-primary);
}

.skills-view__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--space-5);
}

.skills-view__grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: var(--space-4);
}

.skills-view__group {
  margin-bottom: var(--space-6);
}

.skills-view__group-header {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  margin-bottom: var(--space-3);
  padding-bottom: var(--space-2);
  border-bottom: 1px solid var(--border-color-split, rgba(0, 0, 0, 0.06));
}

.skills-view__group-icon {
  font-size: 16px;
  color: var(--color-primary);
}

.skills-view__group-title {
  font-size: var(--font-md, 14px);
  font-weight: 600;
  color: var(--text-primary);
}

.skills-view__group-hint {
  font-size: var(--font-xs, 12px);
  color: var(--text-placeholder);
  margin-left: var(--space-1);
}
</style>
