<template>
  <el-aside class="sidebar" :width="isCollapsed ? (isMobile ? '0' : '64px') : '250px'">
    <div class="sidebar-header">
      <span v-if="!isCollapsed" style="margin-right: 15px; font-weight: bold;">笔记分类</span>
      <el-button v-if="!isCollapsed" type="primary" size="small" @click="$emit('show-create-group')" circle>
        <el-icon><Plus /></el-icon>
      </el-button>
      <el-button @click="$emit('toggle-collapse')" type="primary" size="small" circle v-if="!isMobile">
        <el-icon>
          <Fold v-if="!isCollapsed" />
          <Expand v-else />
        </el-icon>
      </el-button>
    </div>

    <!-- Desktop Menu -->
    <el-menu
        v-if="!isMobile"
        :default-active="activeMenu"
        class="el-menu-vertical-demo"
        :collapse="isCollapsed"
        popper-effect="light"
        :collapse-transition="false"
    >
      <template v-for="menu in categoryTree" :key="menu.id">
        <component :is="renderMenu(menu)" />
      </template>
      <ElMenuItem index="trash" @click="goToTrash">
        <ElIcon><Delete /></ElIcon>
        <template #title>回收站</template>
      </ElMenuItem>
    </el-menu>

    <!-- Mobile Menu -->
    <el-menu
        v-if="isMobile"
        :default-active="activeMenu"
        class="el-menu-vertical-demo"
        :collapse="isCollapsed"
        :collapse-transition="false"
    >
      <div class="mobile-menu-header">
        <div v-if="userStore.isLoggedIn" class="user-info">
          <span class="username">欢迎, {{ userStore.userInfo?.username }}</span>
        </div>
        <div v-else class="guest-info">
          <el-button type="primary" @click="goToLogin">登录</el-button>
          <el-button @click="goToRegister">注册</el-button>
        </div>
      </div>

      <template v-for="menu in categoryTree" :key="menu.id">
        <component :is="renderMenu(menu)" />
      </template>
      <ElMenuItem index="trash" @click="goToTrash">
        <ElIcon><Delete /></ElIcon>
        <template #title>回收站</template>
      </ElMenuItem>
      <ElMenuItem v-if="userStore.isLoggedIn" index="system-settings" @click="$emit('show-system-settings')">
        <ElIcon><setting /></ElIcon>
        <template #title>系统管理</template>
      </ElMenuItem>
      <ElMenuItem v-if="userStore.isLoggedIn" index="update-password" @click="$emit('show-update-password')">
        <ElIcon><lock /></ElIcon>
        <template #title>修改密码</template>
      </ElMenuItem>
      <ElMenuItem v-if="userStore.isLoggedIn" index="logout" @click="$emit('logout')">
        <ElIcon><SwitchButton /></ElIcon>
        <template #title>退出登录</template>
      </ElMenuItem>
    </el-menu>
  </el-aside>
</template>

<script setup>
import { h } from 'vue';
import { ElSubMenu, ElMenuItem, ElIcon, ElMessageBox, ElTooltip, ElMessage } from 'element-plus';
import { Folder, Delete, Edit, Plus, Fold, Expand, Setting, Lock, SwitchButton } from '@element-plus/icons-vue';
import { useUserStore } from '@/stores/user';
import { useRouter } from 'vue-router';
import { deleteGrouping } from '@/api/CommonApi.js';

const props = defineProps({
  isCollapsed: Boolean,
  isMobile: Boolean,
  activeMenu: String,
  categoryTree: Array,
});

const emit = defineEmits([
  'select-file',
  'show-rename-dialog',
  'show-create-group',
  'toggle-collapse',
  'group-deleted',
  'show-system-settings',
  'show-update-password',
  'logout'
]);

const userStore = useUserStore();
const router = useRouter();

const goToTrash = () => router.push({ name: 'Trash' });
const goToLogin = () => router.push('/login');
const goToRegister = () => router.push('/register');

const handleDeleteGroup = (group) => {
  ElMessageBox.confirm(
      `确定要删除分类 “${group.grouping}” 吗？这将同时删除该分类下的所有子分类和笔记。`,
      '警告',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
  ).then(async () => {
    try {
      await deleteGrouping(group.id);
      ElMessage.success('分类已删除');
      emit('group-deleted');
    } catch (error) {
      ElMessage.error('删除分类失败: ' + error.message);
    }
  });
};

const renderMenu = (item) => {
  const titleContent = () => h('div', { class: 'menu-item-title' }, [
    h(ElIcon, () => h(Folder)),
    h('span', { class: 'menu-item-text' }, item.grouping),
    h('div', { class: 'menu-item-actions' }, [
      h(ElIcon, { class: 'edit-icon', onClick: (e) => { e.stopPropagation(); emit('show-rename-dialog', item, 'group'); } }, () => h(Edit)),
      h(ElIcon, { class: 'delete-icon', onClick: (e) => { e.stopPropagation(); handleDeleteGroup(item); } }, () => h(Delete))
    ])
  ]);

  const wrappedContent = () => h(ElTooltip, {
    content: item.grouping,
    placement: 'right',
    disabled: !props.isCollapsed,
    effect: 'dark',
    offset: 15,
  }, { default: titleContent });

  if (item.children && item.children.length > 0) {
    return h(ElSubMenu, {
      index: `group-${item.id}`,
      popperClass: props.isCollapsed ? 'hide-popper' : ''
    }, {
      title: () => h('div', {
        class: 'submenu-title-wrapper',
        onClick: () => emit('select-file', item),
        style: 'width: 100%; display: flex; align-items: center;'
      }, [ wrappedContent() ]),
      default: () => item.children.map(child => renderMenu(child))
    });
  }

  return h(ElMenuItem, { index: `group-${item.id}`, onClick: () => emit('select-file', item) }, {
    default: wrappedContent
  });
};
</script>

<style scoped>
.sidebar {
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  border-right: 1px solid rgba(0, 0, 0, 0.05);
  transition: width 0.3s ease; /* Apply transition to width */
  display: flex;
  flex-direction: column;
}

.dark-theme .sidebar {
  background-color: rgba(23, 23, 39, 0.8);
  border-right: 1px solid rgba(255, 255, 255, 0.1);
}

.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1rem;
  flex-shrink: 0;
}

.el-menu {
  border-right: none;
  background: transparent;
  flex-grow: 1;
  overflow-y: auto;
  overflow-x: hidden;
  transition: none !important; /* Disable built-in transitions */
}

:deep(.el-menu-item), :deep(.el-sub-menu__title) {
  height: 48px;
  line-height: 48px;
  border-radius: var(--border-radius);
  margin: 0.25rem 0.5rem;
  color: var(--text-color-secondary);
}

:deep(.el-menu-item.is-active) {
  background-color: var(--primary-color);
  color: #fff;
  font-weight: 600;
}

:deep(.el-menu-item:hover), :deep(.el-sub-menu__title:hover) {
  background-color: var(--primary-color-light);
  color: var(--primary-color);
}

.menu-item-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  gap: 5px;
}

.menu-item-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex-grow: 1;
  transition: opacity 0.2s ease; /* Add transition for smooth fade */
  opacity: 1;
}

.menu-item-actions {
  display: none;
  align-items: center;
  gap: 5px;
  transition: opacity 0.2s ease;
  opacity: 1;
}

.el-menu:not(.el-menu--collapse) .el-menu-item:hover .menu-item-actions,
.el-menu:not(.el-menu--collapse) .el-sub-menu__title:hover .menu-item-actions {
  display: flex;
}

.el-menu--collapse .menu-item-text,
.el-menu--collapse .menu-item-actions {
  opacity: 0; /* Fade out instead of just disappearing */
  width: 0; /* Ensure it takes no space */
}

.edit-icon, .delete-icon {
  cursor: pointer;
  color: var(--text-color-secondary);
}

.edit-icon:hover, .delete-icon:hover {
  color: var(--primary-color);
}

.mobile-menu-header {
  padding: 20px;
  text-align: center;
  border-bottom: 1px solid #e0e0e0;
}

.mobile-menu-header .username {
  font-weight: bold;
  font-size: 16px;
}
</style>
