<script setup>
import { ref, computed, watch } from 'vue'
import { NModal, NTree, NIcon, NEmpty, NSpin } from 'naive-ui'
import { FolderOutline } from '@vicons/ionicons5'
import { getCategoryTree } from '../../api/category'
import { getWfCategoryTree } from '../../api/wfCategory'

const props = defineProps({
  show: { type: Boolean, default: false },
  // 'skill' | 'workflow'
  categoryType: { type: String, default: 'skill' },
  // 当前已选分类 ID（null 表示未分类）
  selectedId: { type: [Number, null], default: null }
})

const emit = defineEmits(['update:show', 'confirm'])

const loading = ref(false)
const rawData = ref([])
const chosenId = ref(null)

watch(() => props.show, async (val) => {
  if (!val) return
  chosenId.value = props.selectedId
  await loadData()
})

async function loadData() {
  loading.value = true
  try {
    const fetcher = props.categoryType === 'workflow' ? getWfCategoryTree : getCategoryTree
    const res = await fetcher()
    rawData.value = res.data || []
  } catch {} finally {
    loading.value = false
  }
}

// 将后端分类树转为 NTree 需要的格式
const treeData = computed(() => {
  return [
    {
      key: 'uncategorized',
      label: '未分类',
      isUncategorized: true
    },
    ...rawData.value.map(node => convertNode(node))
  ]
})

function convertNode(node) {
  return {
    key: node.id,
    label: `${node.name} (${node.skillCount ?? node.count ?? 0})`,
    children: (node.children && node.children.length)
      ? node.children.map(convertNode)
      : undefined
  }
}

const chosenDisplay = computed(() => {
  if (chosenId.value === null || chosenId.value === 'uncategorized') return '未分类'
  return findLabel(rawData.value, chosenId.value) || `#${chosenId.value}`
})

function findLabel(nodes, id) {
  for (const n of nodes) {
    if (n.id === id) return n.name
    if (n.children) {
      const found = findLabel(n.children, id)
      if (found) return found
    }
  }
  return null
}

function handleSelect(keys) {
  const k = keys[0]
  if (k === 'uncategorized') {
    chosenId.value = null
  } else {
    chosenId.value = k
  }
}

function handleConfirm() {
  emit('confirm', chosenId.value)
  emit('update:show', false)
}
</script>

<template>
  <n-modal
    :show="show"
    preset="card"
    title="选择分类"
    style="max-width: 480px; width: 90vw"
    :bordered="false"
    :closable="false"
    :mask-closable="false"
    @update:show="$emit('update:show', $event)"
  >
    <div v-if="loading" class="picker-loading">
      <n-spin size="small" />
    </div>
    <div v-else-if="treeData.length === 1 && rawData.length === 0" class="picker-empty">
      <n-empty description="暂无分类，请先在分类管理中创建" size="small" />
    </div>
    <div v-else class="picker-body">
      <div class="chosen-hint">
        当前选择：<span class="chosen-name">{{ chosenDisplay }}</span>
      </div>
      <div class="tree-wrapper">
        <n-tree
          :data="treeData"
          :selected-keys="chosenId === null ? ['uncategorized'] : [chosenId]"
          :default-expanded-keys="chosenId !== null ? [chosenId] : []"
          selectable
          block-line
          @update:selected-keys="handleSelect"
        />
      </div>
    </div>

    <template #action>
      <button class="btn-cancel" @click="$emit('update:show', false)">取消</button>
      <button class="btn-save" @click="handleConfirm">确认</button>
    </template>
  </n-modal>
</template>

<style scoped>
.picker-loading {
  display: flex;
  justify-content: center;
  padding: 40px;
}
.picker-empty {
  padding: 30px;
}
.picker-body {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.chosen-hint {
  font-size: 13px;
  color: var(--text-secondary);
  padding: 8px 12px;
  background: rgba(37, 99, 235, 0.06);
  border-radius: 6px;
}
.chosen-name {
  color: var(--color-accent);
  font-weight: 600;
}
.tree-wrapper {
  max-height: 360px;
  overflow-y: auto;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  padding: 8px;
  background: rgba(0, 0, 0, 0.15);
}
.btn-cancel {
  padding: 6px 16px;
  border-radius: 6px;
  border: 1px solid var(--border-color);
  background: transparent;
  color: var(--text-secondary);
  cursor: pointer;
  font-size: 13px;
}
.btn-save {
  padding: 6px 16px;
  border-radius: 6px;
  border: none;
  background: var(--color-accent);
  color: white;
  cursor: pointer;
  font-size: 13px;
  margin-left: 8px;
}
</style>
