<script setup lang="ts">
import { computed, ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { fetchKnowledgeBases } from '@/views/knowledge/useKnowledge'
import { useDatabase } from '@/views/database/useDatabase'
import { useAuth } from '@/composables/useAuth'

// 下拉菜单展开状态
const userDropdownVisible = ref(false)

// 退出确认弹窗状态
const showLogoutConfirm = ref(false)

const router = useRouter()
const route = useRoute()

// 获取当前用户信息
const { getUser, logout: authLogout } = useAuth()
const currentUser = ref(getUser())

// 计算用户首字母缩写
const userInitials = computed(() => {
  const name = currentUser.value?.username || currentUser.value?.name || 'User'
  const parts = name.split(' ')
  if (parts.length >= 2) {
    return (parts[0][0] + parts[1][0]).toUpperCase()
  }
  return name.substring(0, 2).toUpperCase()
})

// 获取 Knowledge 数量
const knowledgeCount = ref(0)
const fetchKnowledgeCount = async () => {
  try {
    const data = await fetchKnowledgeBases()
    knowledgeCount.value = data?.length || 0
  } catch (e) {
    console.error('Failed to fetch knowledge count:', e)
  }
}

// 获取 Database 数量
const { databases, fetchDatabases } = useDatabase()
const databaseCount = computed(() => databases.value?.length || 0)

onMounted(() => {
  fetchKnowledgeCount()
  fetchDatabases()
})

interface MenuItem {
  name: string
  icon: string
  badge?: string | number
  children?: MenuItem[]
  path?: string
}

// 第1组: Chat, Agents
const group1 = computed(() => [
  { name: 'Chat', icon: 'fa-robot', path: '/chat' },
  { name: 'Agents', icon: 'fa-users', badge: 3, path: '/agents' },
])

// 第2组: Database, Knowledge
const group2 = computed(() => [
  { name: 'Database', icon: 'fa-database', path: '/database', badge: databaseCount.value },
  { name: 'Knowledge', icon: 'fa-brain', path: '/knowledge', badge: knowledgeCount.value },
])

// 第3组: Skills, Tools, Script, Plan, Memory
const group3 = computed(() => [
  { name: 'Skills', icon: 'fa-wand-magic-sparkles', badge: 21, path: '/mcp' },
  { name: 'Tools', icon: 'fa-tools', badge: 13, path: '/tools' },
  { name: 'Script', icon: 'fa-code', path: '/script' },
  { name: 'Plan', icon: 'fa-clock', path: '/plan' },
  { name: 'Memory', icon: 'fa-brain', path: '/memory' },
])

// 第4组: Dashboard, Models, Logs
const group4 = computed(() => [
  { name: 'Dashboard', icon: 'fa-gauge', path: '/dashboard' },
  { name: 'Models', icon: 'fa-brain', path: '/settings' },
  { name: 'Logs', icon: 'fa-file-lines', path: '/logs' },
])

const activeMenu = computed(() => {
  const currentPath = route.path

  // Check all groups
  const allGroups = [...group1.value, ...group2.value, ...group3.value, ...group4.value]
  const item = allGroups.find(item => item.path === currentPath)
  if (item) return item.name
  return 'Chat'
})

const navigateTo = (item: MenuItem) => {
  if (item.path) {
    router.push(item.path)
  }
}

// 通知设置弹窗状态
const showNotificationSettings = ref(false)

// 用户菜单操作
const handleUserCommand = (command: string) => {
  switch (command) {
    case 'notifications':
      // 通知设置
      showNotificationSettings.value = true
      break
    case 'account':
      // 账户设置
      router.push('/account')
      break
    case 'userManagement':
      // 用户管理
      router.push('/user-management')
      break
    case 'logout':
      // 退出登录 - 显示自定义确认弹窗
      showLogoutConfirm.value = true
      break
  }
}

// 确认退出登录
const confirmLogout = () => {
  showLogoutConfirm.value = false
  userDropdownVisible.value = false
  authLogout()
  router.push('/login')
}

// 取消退出
const cancelLogout = () => {
  showLogoutConfirm.value = false
}
</script>

<template>
  <aside class="w-64 bg-dark-950 h-screen flex flex-col fixed left-0 top-0 overflow-y-auto scrollbar-hide z-10">
    <!-- 顶部Logo与组织信息 -->
    <div class="p-5 flex items-center gap-3">
      <div class="w-8 h-8 rounded-full bg-gradient-to-br from-primary-orange to-red-500 flex items-center justify-center">
        <i class="fa-solid fa-basketball text-white"></i>
      </div>
      <div>
        <div class="font-semibold text-base flex items-center gap-1 cursor-pointer">
          Organization
          <i class="fa-solid fa-chevron-down text-xs text-gray-500"></i>
        </div>
        <div class="text-sm text-gray-500">Saasfactor</div>
      </div>
    </div>

    <!-- 导航菜单 -->
    <nav class="flex-1 px-3 py-2">
      <ul class="space-y-1">
        <!-- 第1组: Chat, Agents -->
        <li v-for="item in group1" :key="item.name">
          <a
            href="javascript:void(0)"
            class="flex items-center justify-between px-3 py-2.5 rounded-lg transition-colors text-sm"
            :class="activeMenu === item.name ? 'bg-dark-600 text-white' : 'text-gray-400 hover:bg-dark-600 hover:text-white'"
            @click="navigateTo(item)"
          >
            <div class="flex items-center gap-3">
              <i :class="['fa-solid', item.icon, 'w-5', 'text-center']"></i>
              <span>{{ item.name }}</span>
            </div>
            <span v-if="item.badge" class="bg-dark-500 text-xs px-2 py-0.5 rounded-full">{{ item.badge }}</span>
          </a>
        </li>

        <!-- 分隔线1 -->
        <li class="my-4 border-t border-dark-500"></li>

        <!-- 第2组: Database, Knowledge -->
        <li v-for="item in group2" :key="item.name">
          <a
            href="javascript:void(0)"
            class="flex items-center justify-between px-3 py-2.5 rounded-lg transition-colors text-sm"
            :class="activeMenu === item.name ? 'bg-dark-600 text-white' : 'text-gray-400 hover:bg-dark-600 hover:text-white'"
            @click="navigateTo(item)"
          >
            <div class="flex items-center gap-3">
              <i :class="['fa-solid', item.icon, 'w-5', 'text-center']"></i>
              <span>{{ item.name }}</span>
            </div>
            <span v-if="item.badge" class="bg-dark-500 text-xs px-2 py-0.5 rounded-full">{{ item.badge }}</span>
          </a>
        </li>

        <!-- 分隔线2 -->
        <li class="my-4 border-t border-dark-500"></li>

        <!-- 第3组: Skills, Tools, Script -->
        <li v-for="item in group3" :key="item.name">
          <a
            href="javascript:void(0)"
            class="flex items-center justify-between px-3 py-2.5 rounded-lg transition-colors text-sm"
            :class="activeMenu === item.name ? 'bg-dark-600 text-white' : 'text-gray-400 hover:bg-dark-600 hover:text-white'"
            @click="navigateTo(item)"
          >
            <div class="flex items-center gap-3">
              <i :class="['fa-solid', item.icon, 'w-5', 'text-center']"></i>
              <span>{{ item.name }}</span>
            </div>
            <span v-if="item.badge" class="bg-dark-500 text-xs px-2 py-0.5 rounded-full">{{ item.badge }}</span>
          </a>
        </li>

        <!-- 分隔线3 -->
        <li class="my-4 border-t border-dark-500"></li>

        <!-- 第4组: Dashboard, Notifications, Account, Model Settings, Logs -->
        <li v-for="item in group4" :key="item.name">
          <a
            href="javascript:void(0)"
            class="flex items-center justify-between px-3 py-2.5 rounded-lg transition-colors text-sm"
            :class="activeMenu === item.name ? 'bg-dark-600 text-white' : 'text-gray-400 hover:bg-dark-600 hover:text-white'"
            @click="navigateTo(item)"
          >
            <div class="flex items-center gap-3">
              <i :class="['fa-solid', item.icon, 'w-5', 'text-center']"></i>
              <span>{{ item.name }}</span>
            </div>
          </a>
        </li>
      </ul>
    </nav>

    <!-- 底部用户信息 -->
    <div class="border-t border-dark-500">
      <div class="relative">
        <div
          class="w-full flex items-center justify-between cursor-pointer hover:bg-dark-600 px-4 py-3 transition-colors"
          @click="userDropdownVisible = !userDropdownVisible"
        >
          <div class="flex items-center gap-3">
            <div class="w-8 h-8 rounded-full bg-gradient-to-br from-primary-orange to-red-500 flex items-center justify-center text-white font-medium text-xs">
              {{ userInitials }}
            </div>
            <div class="min-w-0">
              <div class="font-medium text-sm text-gray-200 truncate">{{ currentUser?.username || currentUser?.name || 'User' }}</div>
              <div class="text-xs text-gray-500 truncate">{{ currentUser?.email || 'user@example.com' }}</div>
            </div>
          </div>
          <i :class="['fa-solid', userDropdownVisible ? 'fa-chevron-up' : 'fa-chevron-down', 'text-xs', 'text-gray-500']"></i>
        </div>

        <!-- 简洁下拉弹窗 -->
        <Transition name="dropdown-fade">
          <div v-if="userDropdownVisible" class="user-dropdown-panel" @click.stop>
            <div class="dropdown-menu">
              <div class="menu-item" @click="handleUserCommand('notifications')">
                <i class="fa-solid fa-bell text-gray-400"></i>
                <span class="text-gray-300">Notifications</span>
              </div>

              <div class="menu-item" @click="handleUserCommand('account')">
                <i class="fa-solid fa-user text-gray-400"></i>
                <span class="text-gray-300">Account</span>
              </div>

              <div class="menu-item">
                <i class="fa-solid fa-circle-question text-gray-400"></i>
                <span class="text-gray-300">Help & Support</span>
              </div>
            </div>

            <div class="dropdown-divider"></div>

            <div class="dropdown-footer">
              <div class="menu-item logout" @click="handleUserCommand('logout')">
                <i class="fa-solid fa-arrow-right-from-bracket text-gray-400"></i>
                <span class="text-gray-300">Sign Out</span>
              </div>
            </div>
          </div>
        </Transition>
      </div>

      <!-- 点击外部关闭 -->
      <div v-if="userDropdownVisible" class="fixed inset-0 z-40" @click="userDropdownVisible = false"></div>
    </div>
  </aside>

  <!-- 退出确认弹窗 -->
  <Teleport to="body">
    <Transition name="fade">
      <div v-if="showLogoutConfirm" class="fixed inset-0 bg-black/60 flex items-center justify-center z-50" @click="cancelLogout">
        <div class="bg-dark-700 rounded-xl w-full max-w-sm border border-dark-500 shadow-2xl" @click.stop>
          <div class="p-6 text-center">
            <div class="w-14 h-14 rounded-full bg-red-500/20 flex items-center justify-center mx-auto mb-4">
              <i class="fa-solid fa-arrow-right-from-bracket text-red-400 text-xl"></i>
            </div>
            <h3 class="text-lg font-semibold text-white mb-2">Sign Out</h3>
            <p class="text-gray-400 text-sm">Are you sure you want to sign out?</p>
          </div>
          <div class="flex border-t border-dark-500">
            <button @click="cancelLogout" class="flex-1 py-3 text-gray-400 hover:text-white hover:bg-dark-600 transition-colors">
              Cancel
            </button>
            <button @click="confirmLogout" class="flex-1 py-3 text-red-400 hover:bg-red-500/10 transition-colors border-l border-dark-500">
              Sign Out
            </button>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport>

  <!-- 通知设置弹窗 -->
  <Teleport to="body">
    <Transition name="fade">
      <div v-if="showNotificationSettings" class="fixed inset-0 bg-black/60 flex items-center justify-center z-50" @click="showNotificationSettings = false">
        <div class="bg-dark-700 rounded-xl w-full max-w-md border border-dark-500 shadow-2xl" @click.stop>
          <div class="flex items-center justify-between p-5 border-b border-dark-500">
            <h3 class="text-lg font-semibold">Notification Settings</h3>
            <button @click="showNotificationSettings = false" class="text-gray-400 hover:text-white transition-colors">
              <i class="fa-solid fa-xmark text-xl"></i>
            </button>
          </div>
          <div class="p-5 space-y-4">
            <div class="flex items-center justify-between py-3 border-b border-dark-500">
              <div>
                <div class="font-medium text-white">Email Notifications</div>
                <div class="text-sm text-gray-400">Receive email for important updates</div>
              </div>
              <label class="relative inline-flex items-center cursor-pointer">
                <input type="checkbox" class="sr-only peer" checked>
                <div class="w-11 h-6 bg-dark-500 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-orange"></div>
              </label>
            </div>
            <div class="flex items-center justify-between py-3 border-b border-dark-500">
              <div>
                <div class="font-medium text-white">Push Notifications</div>
                <div class="text-sm text-gray-400">Receive push notifications in browser</div>
              </div>
              <label class="relative inline-flex items-center cursor-pointer">
                <input type="checkbox" class="sr-only peer" checked>
                <div class="w-11 h-6 bg-dark-500 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-orange"></div>
              </label>
            </div>
            <div class="flex items-center justify-between py-3 border-b border-dark-500">
              <div>
                <div class="font-medium text-white">System Alerts</div>
                <div class="text-sm text-gray-400">Get notified about system events</div>
              </div>
              <label class="relative inline-flex items-center cursor-pointer">
                <input type="checkbox" class="sr-only peer" checked>
                <div class="w-11 h-6 bg-dark-500 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-orange"></div>
              </label>
            </div>
            <div class="flex items-center justify-between py-3">
              <div>
                <div class="font-medium text-white">Agent Updates</div>
                <div class="text-sm text-gray-400">Notifications about agent activities</div>
              </div>
              <label class="relative inline-flex items-center cursor-pointer">
                <input type="checkbox" class="sr-only peer">
                <div class="w-11 h-6 bg-dark-500 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-orange"></div>
              </label>
            </div>
          </div>
          <div class="flex items-center justify-end gap-3 p-5 border-t border-dark-500">
            <button @click="showNotificationSettings = false" class="px-4 py-2 rounded-lg bg-primary-orange text-white hover:bg-orange-600 transition-colors">
              Save Changes
            </button>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

<style>
/* 用户下拉弹窗 */
.user-dropdown-panel {
  position: absolute;
  bottom: 100%;
  left: 0;
  right: 0;
  margin-bottom: 8px;
  background: #1f1f1f;
  border: 1px solid #404040;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.4);
  z-index: 50;
}

.dropdown-menu {
  padding: 6px;
}

.menu-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.15s ease;
  font-size: 13px;
}

.menu-item:hover {
  background: #333;
}

.dropdown-divider {
  height: 1px;
  background: #333;
  margin: 4px 8px;
}

.dropdown-footer {
  padding: 6px;
}

.menu-item.logout:hover {
  background: rgba(239, 68, 68, 0.15);
}

/* 下拉动画 */
.dropdown-fade-enter-active,
.dropdown-fade-leave-active {
  transition: all 0.15s ease;
}

.dropdown-fade-enter-from,
.dropdown-fade-leave-to {
  opacity: 0;
  transform: translateY(5px);
}

/* 退出确认弹窗动画 */
.fade-enter-active,
.fade-leave-active {
  transition: all 0.2s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
