import { BadgeCheck, Bell, ChevronsUpDown, CreditCard, LogOut, Moon, Sun } from 'lucide-react'
import { Avatar, AvatarFallback, AvatarImage } from '@mdxui/primitives/avatar'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@mdxui/primitives/dropdown-menu'
import {
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  useSidebar,
} from '@mdxui/primitives/sidebar'
import { useAuth } from '../context/auth-context'
import { useNavigation } from '../context/navigation-context'
import { useContext } from 'react'
import { ThemeContext } from '../context/theme-context'
import type { UserIdentity, UserMenuAction } from '../types'

export interface NavUserProps {
  /** User identity (defaults to auth context) */
  user?: UserIdentity
  /** Additional menu actions */
  actions?: UserMenuAction[]
  /** Path for account settings */
  accountPath?: string
  /** Path for billing settings */
  billingPath?: string
  /** Whether to show theme toggle */
  showThemeToggle?: boolean
  /** Whether to show notifications item */
  showNotifications?: boolean
  /** Custom logout handler (defaults to auth context) */
  onLogout?: () => void
}

/**
 * NavUser renders the user menu in the sidebar footer.
 * Shows avatar, user info, and dropdown with actions.
 *
 * @example
 * ```tsx
 * <NavUser
 *   accountPath="/admin/settings"
 *   billingPath="/admin/settings/billing"
 *   showThemeToggle
 *   actions={[
 *     { label: 'API Keys', icon: Key, href: '/admin/settings/api-keys' },
 *   ]}
 * />
 * ```
 */
export function NavUser({
  user: userProp,
  actions = [],
  accountPath = '/settings',
  billingPath = '/settings/billing',
  showThemeToggle = true,
  showNotifications = false,
  onLogout,
}: NavUserProps) {
  const { identity, logout } = useAuth()
  const { Link } = useNavigation()
  const { isMobile } = useSidebar()

  // Use ThemeContext directly - useContext returns null if not in provider
  const themeContext = useContext(ThemeContext)

  const user = userProp ?? identity

  const handleLogout = () => {
    if (onLogout) {
      onLogout()
    } else {
      logout()
    }
  }

  // Fallback user data
  const displayName = user?.fullName ?? 'User'
  const displayEmail = user?.email ?? 'user@example.com'
  const avatarSrc = user?.avatar ?? ''
  const initials = displayName.charAt(0).toUpperCase()

  return (
    <SidebarMenu>
      <SidebarMenuItem>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <SidebarMenuButton
              size="lg"
              className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
            >
              <Avatar className="h-8 w-8 rounded-lg">
                <AvatarImage src={avatarSrc} alt={displayName} />
                <AvatarFallback className="rounded-lg">{initials}</AvatarFallback>
              </Avatar>
              <div className="grid flex-1 text-left text-sm leading-tight">
                <span className="truncate font-medium">{displayName}</span>
                <span className="truncate text-xs">{displayEmail}</span>
              </div>
              <ChevronsUpDown className="ml-auto size-4" />
            </SidebarMenuButton>
          </DropdownMenuTrigger>
          <DropdownMenuContent
            className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
            side={isMobile ? 'bottom' : 'right'}
            align="end"
            sideOffset={4}
          >
            <DropdownMenuLabel className="p-0 font-normal">
              <div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
                <Avatar className="h-8 w-8 rounded-lg">
                  <AvatarImage src={avatarSrc} alt={displayName} />
                  <AvatarFallback className="rounded-lg">{initials}</AvatarFallback>
                </Avatar>
                <div className="grid flex-1 text-left text-sm leading-tight">
                  <span className="truncate font-medium">{displayName}</span>
                  <span className="truncate text-xs">{displayEmail}</span>
                </div>
              </div>
            </DropdownMenuLabel>
            <DropdownMenuSeparator />
            <DropdownMenuGroup>
              <DropdownMenuItem asChild>
                <Link href={accountPath}>
                  <BadgeCheck />
                  Account
                </Link>
              </DropdownMenuItem>
              <DropdownMenuItem asChild>
                <Link href={billingPath}>
                  <CreditCard />
                  Billing
                </Link>
              </DropdownMenuItem>
              {showNotifications && (
                <DropdownMenuItem>
                  <Bell />
                  Notifications
                </DropdownMenuItem>
              )}
              {showThemeToggle && themeContext && (
                <DropdownMenuItem onClick={themeContext.toggleTheme}>
                  {themeContext.resolvedTheme === 'dark' ? <Sun /> : <Moon />}
                  {themeContext.resolvedTheme === 'dark' ? 'Light Mode' : 'Dark Mode'}
                </DropdownMenuItem>
              )}
              {actions.map((action) => (
                <DropdownMenuItem
                  key={action.label}
                  onClick={action.onClick}
                  asChild={!!action.href}
                >
                  {action.href ? (
                    <Link href={action.href}>
                      {action.icon && <action.icon />}
                      {action.label}
                    </Link>
                  ) : (
                    <>
                      {action.icon && <action.icon />}
                      {action.label}
                    </>
                  )}
                </DropdownMenuItem>
              ))}
            </DropdownMenuGroup>
            <DropdownMenuSeparator />
            <DropdownMenuItem onClick={handleLogout}>
              <LogOut />
              Log out
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </SidebarMenuItem>
    </SidebarMenu>
  )
}
