<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Folder, FolderOpened } from '@element-plus/icons-vue'
import { useBookmarkStore } from '@/stores/bookmark'
import type { Folder as FolderType } from '@/types'

const props = withDefaults(defineProps<{
  folders: FolderType[]
  currentFolderId?: string | null
  editable?: boolean
}>(), {
  currentFolderId: null,
  editable: false
})

const emit = defineEmits<{
  select: [folderId: string | null]
  create: [parentId: string | null]
}>()

const bookmarkStore = useBookmarkStore()
const expandedKeys = ref<string[]>([])
const showCreateDialog = ref(false)
const createParentId = ref<string | null>(null)
const newFolderName = ref('')
const creating = ref(false)

// 构建树形数据
const treeData = computed(() => {
  const buildTree = (folders: FolderType[], parentId?: string): any[] => {
    return folders
      .filter(f => f.parentId === parentId)
      .sort((a, b) => a.order - b.order)
      .map(folder => ({
        id: folder.id,
        label: folder.name,
        icon: folder.icon,
        children: buildTree(folders, folder.id)
      }))
  }
  return buildTree(props.folders, undefined)
})

function handleNodeClick(data: { id: string }) {
  emit('select', data.id)
}

function handleSelectAll() {
  emit('select', null)
}

function handleCreateFolder(parentId: string | null = null) {
  createParentId.value = parentId
  newFolderName.value = ''
  showCreateDialog.value = true
}

async function handleConfirmCreate() {
  if (!newFolderName.value.trim()) {
    ElMessage.warning('请输入文件夹名称')
    return
  }

  creating.value = true
  try {
    const response = await bookmarkStore.createFolder(
      newFolderName.value.trim(),
      createParentId.value ?? undefined
    )
    if (response.success) {
      ElMessage.success('创建成功')
      showCreateDialog.value = false
    } else {
      ElMessage.error(response.message || '创建失败')
    }
  } catch {
    ElMessage.error('创建失败')
  } finally {
    creating.value = false
  }
}

async function handleDeleteFolder(folderId: string) {
  try {
    await ElMessageBox.confirm(
      '确定要删除此文件夹吗？文件夹内的书签将移至根目录。',
      '删除确认',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    const response = await bookmarkStore.deleteFolder(folderId)
    if (response.success) {
      ElMessage.success('删除成功')
      if (props.currentFolderId === folderId) {
        emit('select', null)
      }
    }
  } catch {
    // 取消
  }
}
</script>

<template>
  <div class="folder-tree">
    <!-- 全部书签 -->
    <div
      class="folder-item root-item"
      :class="{ active: !currentFolderId }"
      @click="handleSelectAll"
    >
      <el-icon><FolderOpened /></el-icon>
      <span>全部书签</span>
    </div>

    <!-- 文件夹树 -->
    <el-tree
      v-if="treeData.length > 0"
      :data="treeData"
      :expand-on-click-node="false"
      :default-expanded-keys="expandedKeys"
      node-key="id"
      @node-click="handleNodeClick"
    >
      <template #default="{ node, data }">
        <div
          class="folder-item"
          :class="{ active: currentFolderId === data.id }"
        >
          <el-icon><Folder /></el-icon>
          <span class="folder-name">{{ node.label }}</span>
          <div v-if="editable" class="folder-actions" @click.stop>
            <el-button
              size="small"
              :icon="Plus"
              circle
              @click="handleCreateFolder(data.id)"
            />
            <el-button
              size="small"
              :icon="Delete"
              circle
              type="danger"
              @click="handleDeleteFolder(data.id)"
            />
          </div>
        </div>
      </template>
    </el-tree>

    <!-- 空状态 -->
    <div v-else class="empty-tip">
      暂无文件夹
    </div>

    <!-- 创建文件夹按钮 -->
    <div v-if="editable" class="create-folder-btn" @click="handleCreateFolder(null)">
      <el-icon><Plus /></el-icon>
      <span>新建文件夹</span>
    </div>

    <!-- 创建文件夹弹窗 -->
    <el-dialog
      v-model="showCreateDialog"
      title="新建文件夹"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-input
        v-model="newFolderName"
        placeholder="请输入文件夹名称"
        @keyup.enter="handleConfirmCreate"
      />
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" :loading="creating" @click="handleConfirmCreate">
          创建
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.folder-tree {
  .folder-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.2s;
    color: #666;

    &:hover {
      background: #f5f5f5;
    }

    &.active {
      background: #667eea;
      color: #fff;
    }

    &.root-item {
      margin-bottom: 8px;
    }

    .folder-name {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .folder-actions {
      display: none;
      gap: 4px;
    }

    &:hover .folder-actions {
      display: flex;
    }
  }

  .empty-tip {
    padding: 16px;
    text-align: center;
    color: #999;
    font-size: 13px;
  }

  .create-folder-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 12px;
    margin-top: 8px;
    border-radius: 6px;
    cursor: pointer;
    color: #667eea;
    transition: all 0.2s;

    &:hover {
      background: #f0f4ff;
    }
  }

  :deep(.el-tree-node__content) {
    height: auto;
    padding: 0;
  }

  :deep(.el-tree-node__expand-icon) {
    padding: 6px;
  }
}
</style>
