<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-button @click="handleRefresh" :loading="skillsStore.isLoading">
        <template #icon><ReloadOutlined /></template>
        刷新
      </a-button>
    </div>

    <a-spin :spinning="skillsStore.isLoading">
      <div class="skills-view__grid">
        <SkillCard
          v-for="skill in skillsStore.skills"
          :key="skill.name"
          :skill="skill"
          @click="handleSkillClick(skill.name)"
        />
      </div>
      <a-empty v-if="!skillsStore.isLoading && skillsStore.skills.length === 0" description="暂无已注册技能" />
    </a-spin>

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

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ReloadOutlined } from '@ant-design/icons-vue'
import { useSkillsStore } from '@/stores/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)

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()
}
</script>

<style scoped>
.skills-view {
  height: 100%;
  padding: 16px 24px;
  overflow-y: auto;
  background: #fff;
}

.skills-view__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.skills-view__grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}
</style>
