<script setup lang="ts">
import { computed, onMounted, reactive, shallowRef, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { createCategory, createTag, fetchBanks, fetchCategories, fetchTags } from '@/api/admin'
import type { QuestionBank, TaxonomyItem } from '@/types/api'

const loading = shallowRef(false)
const banks = shallowRef<QuestionBank[]>([])
const categories = shallowRef<TaxonomyItem[]>([])
const tags = shallowRef<TaxonomyItem[]>([])
const selectedBankId = shallowRef<number>()
const categoryForm = reactive({
  name: '',
  parent_id: undefined as number | undefined,
  sort: 0,
})
const tagForm = reactive({
  name: '',
})
const activeBank = computed(() => banks.value.find((item) => item.id === selectedBankId.value))

async function loadBanks() {
  const response = await fetchBanks({ per_page: 100 })
  banks.value = response.data.items
  selectedBankId.value = selectedBankId.value ?? banks.value[0]?.id
}

async function loadTaxonomy() {
  if (!selectedBankId.value) return
  loading.value = true
  try {
    const [categoryResponse, tagResponse] = await Promise.all([
      fetchCategories(selectedBankId.value),
      fetchTags(selectedBankId.value),
    ])
    categories.value = categoryResponse.data
    tags.value = tagResponse.data
  } finally {
    loading.value = false
  }
}

async function submitCategory() {
  if (!selectedBankId.value) return
  if (!categoryForm.name.trim()) {
    ElMessage.warning('请输入分类名称')
    return
  }
  await createCategory(selectedBankId.value, {
    name: categoryForm.name.trim(),
    parent_id: categoryForm.parent_id,
    sort: categoryForm.sort,
  })
  ElMessage.success('分类已创建')
  categoryForm.name = ''
  categoryForm.parent_id = undefined
  categoryForm.sort = 0
  await loadTaxonomy()
}

async function submitTag() {
  if (!selectedBankId.value) return
  if (!tagForm.name.trim()) {
    ElMessage.warning('请输入标签名称')
    return
  }
  await createTag(selectedBankId.value, { name: tagForm.name.trim() })
  ElMessage.success('标签已创建')
  tagForm.name = ''
  await loadTaxonomy()
}

watch(selectedBankId, () => {
  void loadTaxonomy()
})

onMounted(async () => {
  await loadBanks()
  await loadTaxonomy()
})
</script>

<template>
  <section class="panel p-5">
    <div class="toolbar mb-4">
      <div class="flex-1">
        <h1 class="page-title">分类标签</h1>
        <p class="muted text-sm mt-1">按题库维护题目分类和标签。</p>
      </div>
      <ElSelect v-model="selectedBankId" class="min-w-60" placeholder="选择题库" filterable>
        <ElOption v-for="item in banks" :key="item.id" :label="item.name" :value="item.id" />
      </ElSelect>
    </div>

    <ElAlert
      v-if="activeBank"
      class="active-bank-alert"
      type="success"
      :closable="false"
      :title="`当前题库：${activeBank.name}`"
    />

    <div class="taxonomy-grid">
      <section class="taxonomy-section">
        <div class="toolbar mb-3">
          <h2 class="section-title">分类</h2>
          <ElTag>{{ categories.length }}</ElTag>
        </div>
        <ElForm :model="categoryForm" label-position="top" class="mb-4">
          <ElFormItem label="分类名称">
            <ElInput v-model="categoryForm.name" />
          </ElFormItem>
          <div class="grid gap-3 md:grid-cols-2">
            <ElFormItem label="父级分类">
              <ElSelect v-model="categoryForm.parent_id" class="w-full" clearable>
                <ElOption v-for="item in categories" :key="item.id" :label="item.name" :value="item.id" />
              </ElSelect>
            </ElFormItem>
            <ElFormItem label="排序">
              <ElInputNumber v-model="categoryForm.sort" class="w-full" :min="0" controls-position="right" />
            </ElFormItem>
          </div>
          <ElButton :icon="Plus" type="primary" @click="submitCategory">新增分类</ElButton>
        </ElForm>
        <ElTable v-loading="loading" :data="categories" row-key="id">
          <ElTableColumn prop="name" label="名称" />
          <ElTableColumn prop="sort" label="排序" width="90" />
        </ElTable>
      </section>

      <section class="taxonomy-section">
        <div class="toolbar mb-3">
          <h2 class="section-title">标签</h2>
          <ElTag type="warning">{{ tags.length }}</ElTag>
        </div>
        <ElForm :model="tagForm" label-position="top" class="mb-4">
          <ElFormItem label="标签名称">
            <ElInput v-model="tagForm.name" />
          </ElFormItem>
          <ElButton :icon="Plus" type="primary" @click="submitTag">新增标签</ElButton>
        </ElForm>
        <div class="tag-board">
          <ElTag v-for="item in tags" :key="item.id" size="large">{{ item.name }}</ElTag>
          <ElEmpty v-if="tags.length === 0" description="暂无标签" />
        </div>
      </section>
    </div>
  </section>
</template>

<style scoped>
.taxonomy-grid {
  display: grid;
  grid-template-columns: minmax(0, 1.2fr) minmax(280px, 0.8fr);
  gap: 16px;
}

.active-bank-alert {
  margin-bottom: 18px;
}

.taxonomy-section {
  min-width: 0;
}

.section-title {
  margin: 0;
  font-size: 16px;
  font-weight: 750;
}

.tag-board {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  min-height: 160px;
  align-content: flex-start;
}

.tag-board :deep(.el-empty) {
  width: 100%;
  margin: auto;
}

@media (max-width: 900px) {
  .taxonomy-grid {
    grid-template-columns: 1fr;
  }
}
</style>
