<script setup lang="ts">
import { ref, watch, onMounted, h } from 'vue'
import { useMessage, NButton, NTag, NSpace, NModal, NInput, NSelect, NIcon, NDataTable, NForm, NFormItem, NInputNumber, NPagination } from 'naive-ui'
import { AddOutline, SearchOutline, RefreshOutline, SaveOutline } from '@vicons/ionicons5'
import { api } from '../../api/client'

interface Tag {
  id: string; name_zh: string | null; name_en: string | null;
  path: string; level: number; tag_category: string;
  is_selectable: boolean; article_count: number;
  source: string; is_active: boolean; mesh_ui: string | null;
}

const message = useMessage()
const items = ref<Tag[]>([])
const total = ref(0)
const loading = ref(true)
const page = ref(1)
const pageSize = ref(20)

const sourceFilter = ref('')
const activeFilter = ref('')
const categoryFilter = ref('')
const searchQuery = ref('')

function doSearch() {
  page.value = 1
  loadData()
}

onMounted(loadData)
watch([page, pageSize], loadData)
watch([sourceFilter, activeFilter, categoryFilter], () => {
  page.value = 1
  loadData()
})

async function loadData() {
  loading.value = true
  try {
    const params: Record<string, any> = { page: page.value, page_size: pageSize.value }
    if (sourceFilter.value) params.source = sourceFilter.value
    if (activeFilter.value) params.active = activeFilter.value
    if (categoryFilter.value) params.category = categoryFilter.value
    if (searchQuery.value) params.q = searchQuery.value.trim()
    const { data } = await api.get('/admin/tags', { params })
    items.value = data.items || []
    total.value = data.total || 0
  } catch (e: any) {
    message.error(e?.response?.data?.detail || '加载标签失败')
  } finally {
    loading.value = false
  }
}



function editTag(t: Tag) {
  editing.value = { ...t }
  showEditModal.value = true
}

async function saveTag() {
  if (!editing.value) return
  saving.value = true
  try {
    await api.put(`/admin/tags/${editing.value.id}`, {
      name_zh: editing.value.name_zh,
      name_en: editing.value.name_en,
      tag_category: editing.value.tag_category,
      is_selectable: editing.value.is_selectable,
      is_active: editing.value.is_active,
    })
    showEditModal.value = false
    message.success('已更新')
    await loadData()
  } catch (e: any) {
    message.error('保存失败：' + (e?.response?.data?.detail || '请重试'))
  } finally {
    saving.value = false
  }
}

async function deleteTag(t: Tag) {
  if (!confirm(`确认删除标签「${t.name_zh || t.name_en}」？将同时删除所有文献关联和用户订阅。`)) return
  try {
    await api.delete(`/admin/tags/${t.id}`)
    message.success('已删除')
    await loadData()
  } catch (e: any) {
    message.error('删除失败：' + (e?.response?.data?.detail || '请重试'))
  }
}

async function refreshCounts() {
  try {
    await api.post('/admin/tags/refresh-counts')
    message.success('文章计数已刷新')
    await loadData()
  } catch (e: any) {
    message.error('刷新失败：' + (e?.response?.data?.detail || '请重试'))
  }
}

async function quickToggleActive(t: Tag) {
  try {
    await api.put(`/admin/tags/${t.id}`, { is_active: !t.is_active })
    if (!t.is_active && t.source === 'auto') {
      await api.put(`/admin/tags/${t.id}`, { source: 'manual', is_active: true })
    }
    await loadData()
  } catch (e: any) {
    message.error('操作失败：' + (e?.response?.data?.detail || '请重试'))
  }
}

async function createTag() {
  saving.value = true
  try {
    await api.post('/admin/tags', creating.value)
    showCreateModal.value = false
    message.success('标签已创建')
    creating.value = { name_zh: '', name_en: '', path: '', tag_category: 'mesh_other', level: 1, parent_id: null }
    await loadData()
  } catch (e: any) {
    message.error('创建失败：' + (e?.response?.data?.detail || '请重试'))
  } finally {
    saving.value = false
  }
}

// ─── Modal State ───
const showEditModal = ref(false)
const editing = ref<any>(null)
const saving = ref(false)

const showCreateModal = ref(false)
const creating = ref({ name_zh: '', name_en: '', path: '', tag_category: 'mesh_other', level: 1, parent_id: null as string | null })

const CAT_OPTIONS = [
  { label: '癌种部位', value: 'cancer' },
  { label: '驱动基因/靶点', value: 'gene' },
  { label: '治疗方式', value: 'treatment' },
  { label: '研究类型', value: 'study_type' },
  { label: '临床终点', value: 'endpoint' },
  { label: '临床场景', value: 'scenario' },
  { label: '其他', value: 'mesh_other' },
]

const CATEGORY_OPTIONS = [
  { label: '全部', value: '' },
  ...CAT_OPTIONS,
]

const SOURCE_OPTIONS = [
  { label: '全部', value: '' },
  { label: '手工', value: 'manual' },
  { label: 'MeSH', value: 'mesh' },
  { label: '自动', value: 'auto' },
]

const ACTIVE_OPTIONS = [
  { label: '全部', value: '' },
  { label: '已激活', value: 'true' },
  { label: '未激活', value: 'false' },
]

const cols = [
  { title: '中文名', key: 'name_zh', width: 120, ellipsis: true, render: (r: Tag) => r.name_zh || h('span', { style: 'color:var(--text-muted)' }, '(空)') },
  { title: '英文名', key: 'name_en', width: 180, ellipsis: true, render: (r: Tag) => r.name_en || '—' },
  { title: '路径', key: 'path', width: 200, ellipsis: { tooltip: true } },
  { title: '级别', key: 'level', width: 50 },
  { title: '类别', key: 'tag_category', width: 80, render: (r: Tag) => {
    const label = CAT_OPTIONS.find(o => o.value === r.tag_category)?.label || r.tag_category
    return h(NTag, { size: 'tiny' }, label)
  }},
  { title: '来源', key: 'source', width: 80, render: (r: Tag) => {
    const m: Record<string, string> = { manual: '手工', mesh: 'MeSH', auto: '自动' }
    const t: Record<string, 'success' | 'info' | 'warning' | 'default'> = { manual: 'success', mesh: 'info', auto: 'warning' }
    return h(NTag, { size: 'tiny', type: t[r.source] || 'default' }, m[r.source] || r.source)
  }},
  { title: '状态', key: 'is_active', width: 60, render: (r: Tag) => {
    return h(NButton, {
      size: 'tiny',
      type: r.is_active ? 'success' : 'warning',
      quaternary: true,
      onClick: () => quickToggleActive(r),
    }, r.is_active ? '✓ 激活' : '未激活')
  }},
  { title: '可选', key: 'is_selectable', width: 50, render: (r: Tag) => h(NTag, { size: 'tiny', type: r.is_selectable ? 'success' : 'default' }, r.is_selectable ? '是' : '否') },
  { title: '文献数', key: 'article_count', width: 70 },
  { title: 'MeSH UI', key: 'mesh_ui', width: 90, ellipsis: true, render: (r: Tag) => r.mesh_ui || '—' },
  { title: '操作', key: 'actions', width: 90, render: (r: Tag) => h(NSpace, {}, [
    h(NButton, { size: 'tiny', quaternary: true, onClick: () => editTag(r) }, '编辑'),
    h(NButton, { size: 'tiny', quaternary: true, type: 'error', onClick: () => deleteTag(r) }, '删除'),
  ])},
]
const scrollX = 1070
</script>

<template>
  <div>
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;flex-wrap:wrap;gap:8px">
      <h2 style="margin:0">标签管理 ({{ total }})</h2>
      <NSpace wrap>
        <NInput v-model:value="searchQuery" placeholder="搜索中文名/英文名/类别" size="small" style="width:200px" clearable @keyup.enter="doSearch" @clear="doSearch" />
	        <NButton size="small" @click="doSearch" class="sky-btn"><template #icon><NIcon size="14"><SearchOutline /></NIcon></template>查询</NButton>
        <span style="font-size:12px;color:var(--text-muted);line-height:28px">来源</span>
        <NSelect v-model:value="sourceFilter" :options="SOURCE_OPTIONS" placeholder="来源" size="small" style="width:100px" />
        <span style="font-size:12px;color:var(--text-muted);line-height:28px">类别</span>
        <NSelect v-model:value="categoryFilter" :options="CATEGORY_OPTIONS" placeholder="类别" size="small" style="width:120px" />
        <span style="font-size:12px;color:var(--text-muted);line-height:28px">状态</span>
        <NSelect v-model:value="activeFilter" :options="ACTIVE_OPTIONS" placeholder="状态" size="small" style="width:100px" />
        <NButton size="small" @click="showCreateModal = true" class="sky-btn"><template #icon><NIcon size="14"><AddOutline /></NIcon></template>新建标签</NButton>
        <NButton size="small" @click="refreshCounts" class="sky-btn"><template #icon><NIcon size="14"><RefreshOutline /></NIcon></template>刷新计数</NButton>
      </NSpace>
    </div>

    <NDataTable :columns="cols" :data="items" :loading="loading" size="small" :bordered="false" :row-key="(r:Tag)=>r.id" :scroll-x="scrollX" />

    <div v-if="total > 0" style="display:flex;justify-content:center;margin-top:16px">
      <NPagination v-model:page="page" :page-count="Math.ceil(total / pageSize)" :page-size="pageSize"
        @update:page-size="pageSize = $event; page = 1" :page-sizes="[20, 50, 100, 200]" show-size-picker />
    </div>

    <!-- Edit Modal -->
    <NModal v-model:show="showEditModal" title="编辑标签" v-if="editing" preset="card" style="width:500px" closable>
      <NForm label-placement="left" label-width="80" :show-feedback="false">
        <NFormItem label="中文名"><NInput v-model:value="editing.name_zh" placeholder="留空则显示英文" /></NFormItem>
        <NFormItem label="英文名"><NInput v-model:value="editing.name_en" /></NFormItem>
        <NFormItem label="路径">{{ editing.path }}</NFormItem>
        <NFormItem label="类别">
          <NSelect v-model:value="editing.tag_category" :options="CAT_OPTIONS" />
        </NFormItem>
        <NFormItem label="来源" v-if="editing">
          <NTag :type="(editing.source === 'manual' ? 'success' : editing.source === 'mesh' ? 'info' : 'warning') as any" size="small">
            {{ SOURCE_OPTIONS.find(o => o.value === editing.source)?.label || editing.source }}
          </NTag>
        </NFormItem>
        <NFormItem label="激活">
          <NSelect :value="editing.is_active ? 'yes' : 'no'" @update:value="v => editing.is_active = v === 'yes'"
            :options="[{label:'已激活',value:'yes'},{label:'未激活',value:'no'}]" />
        </NFormItem>
        <NFormItem label="可选">
          <NSelect :value="editing.is_selectable ? 'yes' : 'no'" @update:value="v => editing.is_selectable = v === 'yes'"
            :options="[{label:'是',value:'yes'},{label:'否',value:'no'}]" />
        </NFormItem>
        <NFormItem label="文献数">{{ editing.article_count }}</NFormItem>
        <NButton type="primary" :loading="saving" @click="saveTag" class="sky-btn" style="margin-top:8px">
          <template #icon><NIcon size="14"><SaveOutline /></NIcon></template>保存
        </NButton>
      </NForm>
    </NModal>

    <!-- Create Modal -->
    <NModal v-model:show="showCreateModal" title="新建标签" preset="card" style="width:500px" closable>
      <NForm label-placement="left" label-width="80">
        <NFormItem label="中文名"><NInput v-model:value="creating.name_zh" placeholder="必填" /></NFormItem>
        <NFormItem label="英文名"><NInput v-model:value="creating.name_en" placeholder="可选" /></NFormItem>
        <NFormItem label="路径"><NInput v-model:value="creating.path" placeholder="如 癌种::肺癌" /></NFormItem>
        <NFormItem label="级别"><NInputNumber v-model:value="creating.level" :min="1" :max="5" /></NFormItem>
        <NFormItem label="类别"><NSelect v-model:value="creating.tag_category" :options="CAT_OPTIONS" /></NFormItem>
        <NButton type="primary" :loading="saving" @click="createTag" class="sky-btn">
          <template #icon><NIcon size="14"><AddOutline /></NIcon></template>创建
        </NButton>
      </NForm>
    </NModal>
  </div>
</template>
