<script setup lang="ts">
import { computed, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, ArrowDown } from '@element-plus/icons-vue'
import type { Tag, TagGroup } from '@/types'
import { tagsApi } from '@/api/tags'
import { tagGroupsApi } from '@/api/tag-groups'

const props = defineProps<{
  tags: Tag[]
  tagGroups: TagGroup[]
  selected: string[]
}>()

const emit = defineEmits<{
  (e: 'update:selected', v: string[]): void
  /** 标签/分组变化后由父级刷新字典 */
  (e: 'dictionaries-changed'): void
}>()

const selectedTagIds = computed({
  get: () => props.selected,
  set: (v: string[]) => emit('update:selected', v),
})

interface TreeNode {
  id: string
  rawId: string | null
  type: 'group' | 'tag'
  label: string
  disabled?: boolean
  children?: TreeNode[]
}

const tagPopoverVisible = ref(false)
const hoveredNodeId = ref<string | null>(null)

const MAX_VISIBLE_TAGS = 1

const displayedSelectedTagIds = computed(() =>
  selectedTagIds.value.slice(0, MAX_VISIBLE_TAGS),
)
const hiddenSelectedCount = computed(() =>
  Math.max(0, selectedTagIds.value.length - MAX_VISIBLE_TAGS),
)

function getTagName(id: string): string {
  return props.tags.find((t) => t.id === id)?.tagName ?? id
}

function removeSelectedTag(id: string): void {
  selectedTagIds.value = selectedTagIds.value.filter((v) => v !== id)
}

function toggleTagInSelection(tagId: string): void {
  if (selectedTagIds.value.includes(tagId)) {
    selectedTagIds.value = selectedTagIds.value.filter((v) => v !== tagId)
  } else {
    selectedTagIds.value = [...selectedTagIds.value, tagId]
  }
}

const tagTreeData = computed<TreeNode[]>(() => {
  const groupNodes: TreeNode[] = props.tagGroups
    .slice()
    .sort((a, b) => a.sortOrder - b.sortOrder)
    .map((g) => ({
      id: `g-${g.id}`,
      rawId: g.id,
      type: 'group' as const,
      label: g.groupName,
      children: props.tags
        .filter((t) => t.tagGroupId === g.id)
        .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0))
        .map((t) => ({
          id: `t-${t.id}`,
          rawId: t.id,
          type: 'tag' as const,
          label: t.tagName,
        })),
    }))

  const ungrouped: TreeNode[] = props.tags
    .filter((t) => !t.tagGroupId)
    .sort((a, b) => a.tagName.localeCompare(b.tagName))
    .map((t) => ({
      id: `t-${t.id}`,
      rawId: t.id,
      type: 'tag' as const,
      label: t.tagName,
    }))

  if (ungrouped.length > 0) {
    groupNodes.push({
      id: 'g-ungrouped',
      rawId: null,
      type: 'group',
      label: '未分组',
      disabled: true,
      children: ungrouped,
    })
  }
  return groupNodes
})

function onTreeNodeClick(data: TreeNode): void {
  if (data.type === 'group' && !data.disabled) {
    // 点击分组 = 全选/取消该组全部标签
    const tagIds = (data.children ?? []).map((c) => c.rawId!).filter(Boolean)
    if (tagIds.length === 0) return
    const allSelected = tagIds.every((id) => selectedTagIds.value.includes(id))
    if (allSelected) {
      selectedTagIds.value = selectedTagIds.value.filter((id) => !tagIds.includes(id))
    } else {
      selectedTagIds.value = [...new Set([...selectedTagIds.value, ...tagIds])]
    }
  }
}

// ─── 标签编辑小弹窗 ───
const tagEditVisible = ref(false)
const tagEditForm = ref({ id: '', tagName: '', tagColor: '#ff6800', tagFontColor: '#ffffff' })
const tagEditLoading = ref(false)

function openTagEdit(t: Tag) {
  tagEditForm.value = { id: t.id, tagName: t.tagName, tagColor: t.tagColor || '#ff6800', tagFontColor: t.tagFontColor || '#ffffff' }
  tagEditVisible.value = true
}

function openTagEditById(id: string): void {
  const t = props.tags.find((tag) => tag.id === id)
  if (t) openTagEdit(t)
}

async function handleTagEditSubmit() {
  if (!tagEditForm.value.tagName.trim()) { ElMessage.warning('请输入标签名称'); return }
  tagEditLoading.value = true
  try {
    await tagsApi.updateTag(tagEditForm.value.id, { tagName: tagEditForm.value.tagName.trim(), tagColor: tagEditForm.value.tagColor, tagFontColor: tagEditForm.value.tagFontColor } as any)
    ElMessage.success('保存成功')
    tagEditVisible.value = false
    emit('dictionaries-changed')
  } catch (e: any) { ElMessage.error(e?.response?.data?.message || '操作失败') }
  finally { tagEditLoading.value = false }
}

async function handleTagEditDelete() {
  try {
    await ElMessageBox.confirm(`确定删除标签「${tagEditForm.value.tagName}」吗？`, '确认', { type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' })
  } catch { return }
  try {
    await tagsApi.deleteTag(tagEditForm.value.id)
    ElMessage.success('删除成功')
    tagEditVisible.value = false
    emit('dictionaries-changed')
  } catch { ElMessage.error('删除失败') }
}

// ─── 分组编辑小弹窗 ───
const groupEditVisible = ref(false)
const groupEditLoading = ref(false)
const groupEditForm = ref<{ id: string; groupName: string }>({ id: '', groupName: '' })

function openGroupEdit(node: TreeNode): void {
  // 虚拟「未分组」节点不可编辑
  if (node.id === 'g-ungrouped') return
  groupEditForm.value = { id: node.rawId!, groupName: node.label }
  groupEditVisible.value = true
}

async function handleGroupSave(): Promise<void> {
  const name = groupEditForm.value.groupName.trim()
  if (!name) { ElMessage.warning('请输入分组名称'); return }
  groupEditLoading.value = true
  try {
    await tagGroupsApi.updateTagGroup(groupEditForm.value.id, { groupName: name })
    ElMessage.success('已保存')
    groupEditVisible.value = false
    emit('dictionaries-changed')
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || '保存失败')
  } finally {
    groupEditLoading.value = false
  }
}

async function handleGroupDelete(): Promise<void> {
  try {
    await ElMessageBox.confirm(
      `删除分组「${groupEditForm.value.groupName}」后，组内标签将归为「未分组」。确认删除？`,
      '确认删除',
      { type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' },
    )
  } catch { return }
  groupEditLoading.value = true
  try {
    await tagGroupsApi.deleteTagGroup(groupEditForm.value.id)
    ElMessage.success('已删除')
    groupEditVisible.value = false
    emit('dictionaries-changed')
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || '删除失败')
  } finally {
    groupEditLoading.value = false
  }
}

async function quickCreateTagGroup() {
  try {
    const { value } = await ElMessageBox.prompt('请输入分组名称', '新建分组', {
      confirmButtonText: '新建', cancelButtonText: '取消', inputPlaceholder: '分组名称',
    })
    if (!value.trim()) return
    const maxSort = Math.max(0, ...props.tagGroups.map((g) => g.sortOrder))
    await tagGroupsApi.createTagGroup({ groupName: value.trim(), sortOrder: maxSort + 1 } as any)
    ElMessage.success('已创建分组')
    emit('dictionaries-changed')
  } catch {}
}
</script>

<template>
  <el-popover
    v-model:visible="tagPopoverVisible"
    placement="bottom-start"
    :width="280"
    trigger="click"
    transition="el-zoom-in-top"
    popper-class="tag-filter-popper"
  >
    <template #reference>
      <div
        class="tag-select-trigger"
        :class="{ 'is-filled': selectedTagIds.length > 0, 'is-active': tagPopoverVisible }"
      >
        <template v-if="selectedTagIds.length === 0">
          <span class="placeholder">标签筛选</span>
        </template>
        <template v-else>
          <el-tag
            v-for="id in displayedSelectedTagIds"
            :key="id"
            size="small"
            closable
            type="info"
            @close.stop="removeSelectedTag(id)"
          >
            {{ getTagName(id) }}
          </el-tag>
          <span v-if="hiddenSelectedCount > 0" class="more-tag">+{{ hiddenSelectedCount }}</span>
        </template>
        <el-icon class="tag-arrow"><ArrowDown /></el-icon>
      </div>
    </template>

    <div class="tag-tree-panel">
      <div class="tag-tree-toolbar">
        <el-button text size="small" :icon="Plus" @click="quickCreateTagGroup">新建分组</el-button>
      </div>
      <el-tree
        :data="tagTreeData"
        node-key="id"
        default-expand-all
        :props="{ label: 'label', children: 'children' }"
        @node-click="onTreeNodeClick"
      >
        <template #default="{ data }">
          <div
            class="tree-row"
            :class="{
              'is-group': data.type === 'group',
              'is-tag': data.type === 'tag',
              'is-disabled': data.disabled,
              'is-checked': data.type === 'tag' && selectedTagIds.includes(data.rawId),
            }"
            @mouseenter="hoveredNodeId = data.id"
            @mouseleave="hoveredNodeId = null"
          >
            <template v-if="data.type === 'group'">
              <i class="fa-solid fa-folder node-icon" />
              <span class="node-label">
                {{ data.label }}
                <span v-if="data.children && data.children.length" class="node-count">{{ data.children.length }}</span>
              </span>
              <span v-show="hoveredNodeId === data.id" class="node-actions">
                <el-button text size="small" :icon="Edit" title="编辑分组" @click.stop="openGroupEdit(data)" />
              </span>
            </template>
            <template v-else>
              <el-checkbox
                :model-value="selectedTagIds.includes(data.rawId)"
                @change="toggleTagInSelection(data.rawId)"
                @click.stop
              />
              <span class="node-label">{{ data.label }}</span>
              <span v-show="hoveredNodeId === data.id" class="node-actions">
                <el-button text size="small" :icon="Edit" title="编辑标签" @click.stop="openTagEditById(data.rawId)" />
              </span>
            </template>
          </div>
        </template>
      </el-tree>
    </div>
  </el-popover>

  <!-- Tag Edit Modal -->
  <el-dialog v-model="tagEditVisible" title="编辑标签" width="420px" destroy-on-close>
    <el-form label-width="80px">
      <el-form-item label="名称"><el-input v-model="tagEditForm.tagName" placeholder="标签名称" /></el-form-item>
      <el-form-item label="背景色">
        <div style="display: flex; align-items: center; gap: 8px;">
          <el-color-picker v-model="tagEditForm.tagColor" />
          <el-input v-model="tagEditForm.tagColor" placeholder="#ff6800" style="width: 120px" />
        </div>
      </el-form-item>
      <el-form-item label="字体色">
        <div style="display: flex; align-items: center; gap: 8px;">
          <el-color-picker v-model="tagEditForm.tagFontColor" />
          <el-input v-model="tagEditForm.tagFontColor" placeholder="#ffffff" style="width: 120px" />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="danger" :loading="tagEditLoading" @click="handleTagEditDelete">删除</el-button>
      <el-button @click="tagEditVisible = false">取消</el-button>
      <el-button type="primary" :loading="tagEditLoading" @click="handleTagEditSubmit">保存</el-button>
    </template>
  </el-dialog>

  <!-- Group Edit Modal -->
  <el-dialog
    v-model="groupEditVisible"
    :title="`编辑分组「${groupEditForm.groupName}」`"
    width="420px"
    destroy-on-close
  >
    <el-form label-width="80px">
      <el-form-item label="分组名称">
        <el-input v-model="groupEditForm.groupName" placeholder="请输入分组名称" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="danger" :loading="groupEditLoading" @click="handleGroupDelete">删除</el-button>
      <el-button @click="groupEditVisible = false">取消</el-button>
      <el-button type="primary" :loading="groupEditLoading" @click="handleGroupSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
/* Custom trigger that looks like el-select */
.tag-select-trigger {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  width: 180px;
  min-height: 24px;
  padding: 0 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: #fff;
  font-size: 12px;
  color: #606266;
  cursor: pointer;
  transition: border-color 0.2s;
  box-sizing: border-box;
}
.tag-select-trigger:hover {
  border-color: #c0c4cc;
}
.tag-select-trigger.is-active {
  border-color: var(--brand-color);
}
.tag-select-trigger .placeholder {
  color: #a8abb2;
}
.tag-select-trigger .tag-arrow {
  margin-left: auto;
  font-size: 12px;
  color: #a8abb2;
  transition: transform 0.3s ease, color 0.2s;
  flex-shrink: 0;
}
.tag-select-trigger.is-active .tag-arrow {
  transform: rotate(180deg);
  color: var(--brand-color);
}
.tag-select-trigger.is-filled {
  color: #111;
}
.tag-select-trigger .more-tag {
  display: inline-flex;
  align-items: center;
  height: 20px;
  padding: 0 6px;
  background: #f4f4f5;
  border-radius: 3px;
  font-size: 11px;
  color: #606266;
}
</style>

<style>
/* Popover 挂载在 body 下，需要全局样式 */
.tag-filter-popper {
  padding: 0 !important;
}
.tag-filter-popper .tag-tree-panel {
  max-height: 380px;
  overflow-y: auto;
  padding: 4px 0;
}
.tag-tree-toolbar {
  padding: 4px 8px 6px;
  border-bottom: 1px solid #f0f0f0;
}
.tag-filter-popper .el-tree {
  padding: 0 4px;
}

/* Tree row layout */
.tag-filter-popper .tree-row {
  display: flex;
  align-items: center;
  gap: 6px;
  width: 100%;
  padding: 4px 6px;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  position: relative;
}
.tag-filter-popper .tree-row.is-group {
  font-weight: 600;
  color: #111;
  background: #fafafa;
}
.tag-filter-popper .tree-row.is-group:hover {
  background: #f0f0f0;
}
.tag-filter-popper .tree-row.is-tag:hover {
  background: #f5f7fa;
}
.tag-filter-popper .tree-row.is-tag.is-checked {
  background: #fff2e8;
  color: #ff6a00;
}
.tag-filter-popper .node-icon {
  color: #f59e0b;
  font-size: 12px;
  width: 14px;
  text-align: center;
  flex-shrink: 0;
}
.tag-filter-popper .node-label {
  flex: 1;
  user-select: none;
}
.tag-filter-popper .node-count {
  display: inline-block;
  margin-left: 4px;
  padding: 0 5px;
  font-size: 10px;
  color: #909399;
  background: #e9e9eb;
  border-radius: 8px;
  font-weight: 400;
}
.tag-filter-popper .node-actions {
  display: inline-flex;
  gap: 0;
  margin-left: auto;
  flex-shrink: 0;
}
.tag-filter-popper .node-actions .el-button {
  padding: 2px 4px;
}
</style>
