<template>
  <SidebarMenu>
    <SidebarMenuItem>
      <DropdownMenu>
        <DropdownMenuTrigger as-child>
          <SidebarMenuButton
            size="lg"
            class="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
          >
            <Avatar class="h-8 w-8 rounded-lg">
              <AvatarImage :src="userAvatar" :alt="userDisplayName" />
              <AvatarFallback class="rounded-lg">
                {{ userInitials }}
              </AvatarFallback>
            </Avatar>
            <div class="grid flex-1 text-left text-sm leading-tight">
              <span class="truncate font-semibold">{{ userDisplayName }}</span>
              <span class="truncate text-xs capitalize">{{ user?.role }}</span>
            </div>
            <ChevronsUpDown class="ml-auto size-4" />
          </SidebarMenuButton>
        </DropdownMenuTrigger>
        <DropdownMenuContent
          class="w-[--reka-dropdown-menu-trigger-width] min-w-56 rounded-lg"
          :side="isMobile ? 'bottom' : 'right'"
          align="end"
          :side-offset="4"
        >
          <DropdownMenuLabel class="p-0 font-normal">
            <div class="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
              <Avatar class="h-8 w-8 rounded-lg">
                <AvatarImage :src="userAvatar" :alt="userDisplayName" />
                <AvatarFallback class="rounded-lg">
                  {{ userInitials }}
                </AvatarFallback>
              </Avatar>
              <div class="grid flex-1 text-left text-sm leading-tight">
                <span class="truncate font-semibold">{{ userDisplayName }}</span>
                <span class="truncate text-xs">{{ user?.email }}</span>
              </div>
            </div>
          </DropdownMenuLabel>
          <DropdownMenuSeparator />
          
          <!-- Role-specific features -->
          <DropdownMenuGroup v-if="showRoleFeatures">
            <DropdownMenuItem v-if="user?.role === 'developer'" @click="navigateTo('/developer/api-keys')">
              <Key class="size-4" />
              API Keys
            </DropdownMenuItem>
            <DropdownMenuItem v-if="isAdminOrCoordinator" @click="navigateTo('/users')">
              <Users class="size-4" />
              Team Management
            </DropdownMenuItem>
            <DropdownMenuItem v-if="user?.is_admin" @click="navigateTo('/settings')">
              <Settings class="size-4" />
              System Settings
            </DropdownMenuItem>
          </DropdownMenuGroup>
          <DropdownMenuSeparator v-if="showRoleFeatures" />
          
          <!-- User account options -->
          <DropdownMenuGroup>
            <DropdownMenuItem @click="navigateTo('/profile')">
              <User class="size-4" />
              Profile
            </DropdownMenuItem>
            <DropdownMenuItem @click="navigateTo('/settings/preferences')">
              <Palette class="size-4" />
              Preferences
            </DropdownMenuItem>
            <DropdownMenuItem @click="toggleNotifications">
              <Bell class="size-4" />
              Notifications
              <span class="ml-auto text-xs text-muted-foreground">
                {{ notificationsEnabled ? 'On' : 'Off' }}
              </span>
            </DropdownMenuItem>
          </DropdownMenuGroup>
          <DropdownMenuSeparator />
          
          <!-- Help and support -->
          <DropdownMenuGroup>
            <DropdownMenuItem @click="navigateTo('/help')">
              <HelpCircle class="size-4" />
              Help & Support
            </DropdownMenuItem>
            <DropdownMenuItem @click="showKeyboardShortcuts">
              <Keyboard class="size-4" />
              Keyboard Shortcuts
            </DropdownMenuItem>
          </DropdownMenuGroup>
          <DropdownMenuSeparator />
          
          <!-- Logout -->
          <DropdownMenuItem @click="handleLogout" class="text-destructive focus:text-destructive">
            <LogOut class="size-4" />
            Log out
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </SidebarMenuItem>
  </SidebarMenu>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import {
  ChevronsUpDown,
  LogOut,
  User,
  Settings,
  Bell,
  Key,
  Users,
  Palette,
  HelpCircle,
  Keyboard,
} from 'lucide-vue-next'
import {
  Avatar,
  AvatarFallback,
  AvatarImage,
} from '@/components/ui/avatar'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  useSidebar,
} from '@/components/ui/sidebar'
import { useAuthStore } from '@/stores/auth'


const router = useRouter()
const { isMobile } = useSidebar()
const authStore = useAuthStore()

// User data
const user = computed(() => authStore.user)

// User display information
const userDisplayName = computed(() => {
  if (!user.value) return 'Guest'
  return `${user.value.first_name} ${user.value.last_name}`
})

const userInitials = computed(() => {
  if (!user.value) return 'G'
  const firstInitial = user.value.first_name?.charAt(0) || ''
  const lastInitial = user.value.last_name?.charAt(0) || ''
  return (firstInitial + lastInitial).toUpperCase()
})

const userAvatar = computed(() => {
  // Use uploaded avatar if available
  if (user.value?.avatar_url) {
    // Use direct static file serving
    const cleanUrl = user.value.avatar_url.replace(/^backend[\/\\]/, '').replace(/\\/g, '/')
    return `/${cleanUrl}`
  }
  // Return empty string to show fallback initials
  return ''
})

// Role-based features
const isAdminOrCoordinator = computed(() => {
  return user.value?.is_admin || user.value?.role === 'coordinator'
})

const showRoleFeatures = computed(() => {
  return user.value?.role === 'developer' || isAdminOrCoordinator.value || user.value?.is_admin
})

// Notifications state (this would typically come from a notifications store)
const notificationsEnabled = ref(true)

// Actions
const navigateTo = (path: string) => {
  router.push(path)
}

const handleLogout = async () => {
  try {
    await authStore.logout()
    router.push('/login')
  } catch (error) {
    console.error('Logout failed:', error)
  }
}

const toggleNotifications = () => {
  notificationsEnabled.value = !notificationsEnabled.value
  // In a real app, this would update user preferences
  console.log('Notifications toggled:', notificationsEnabled.value)
}

const showKeyboardShortcuts = () => {
  // In a real app, this would open a modal with keyboard shortcuts
  console.log('Keyboard shortcuts modal would open here')
  // For now, just show an alert with some common shortcuts
  alert(`Keyboard Shortcuts:
  
⌘/Ctrl + B - Toggle sidebar
⌘/Ctrl + K - Quick search
⌘/Ctrl + , - Open preferences
⌘/Ctrl + / - Show help

More shortcuts available in the help documentation.`)
}



</script>