'use client'

import { useState } from 'react'
import Link from 'next/link'
import type { Route } from 'next'
import { usePathname } from 'next/navigation'
import { signOut } from 'next-auth/react'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Separator } from '@/components/ui/separator'
import {
  LayoutDashboard,
  FolderKanban,
  Users,
  ClipboardList,
  Settings,
  FileSpreadsheet,
  Menu,
  X,
  LogOut,
  ChevronRight,
  BookOpen,
  Handshake,
  CircleDot,
  History,
  Trophy,
  User,
  MessageSquare,
  LayoutTemplate,
} from 'lucide-react'
import { getInitials } from '@/lib/utils'
import { Logo } from '@/components/shared/logo'
import { EditionSelector } from '@/components/shared/edition-selector'
import { useEdition } from '@/contexts/edition-context'
import { UserAvatar } from '@/components/shared/user-avatar'
import { NotificationBell } from '@/components/shared/notification-bell'
import { useSession } from 'next-auth/react'
import { trpc } from '@/lib/trpc/client'

interface AdminSidebarProps {
  user: {
    name?: string | null
    email?: string | null
    role?: string
  }
}

type NavItem = {
  name: string
  href: string
  icon: typeof LayoutDashboard
  activeMatch?: string   // pathname must include this to be active
  activeExclude?: string // pathname must NOT include this to be active
  subItems?: { name: string; href: string }[]
}

// Main navigation - scoped to selected edition
const navigation: NavItem[] = [
  {
    name: 'Dashboard',
    href: '/admin',
    icon: LayoutDashboard,
  },
  {
    name: 'Rounds',
    href: '/admin/rounds/pipelines',
    icon: CircleDot,
  },
  {
    name: 'Awards',
    href: '/admin/awards',
    icon: Trophy,
  },
  {
    name: 'Projects',
    href: '/admin/projects',
    icon: ClipboardList,
  },
  {
    name: 'Members',
    href: '/admin/members',
    icon: Users,
  },
  {
    name: 'Reports',
    href: '/admin/reports',
    icon: FileSpreadsheet,
  },
  {
    name: 'Learning Hub',
    href: '/admin/learning',
    icon: BookOpen,
  },
  {
    name: 'Messages',
    href: '/admin/messages',
    icon: MessageSquare,
  },
  {
    name: 'Partners',
    href: '/admin/partners',
    icon: Handshake,
  },
]

// Admin-only navigation
const adminNavigation: NavItem[] = [
  {
    name: 'Manage Editions',
    href: '/admin/programs',
    icon: FolderKanban,
    activeExclude: 'apply-settings',
  },
  {
    name: 'Apply Page',
    href: '/admin/programs',
    icon: LayoutTemplate,
    activeMatch: 'apply-settings',
  },
  {
    name: 'Audit Log',
    href: '/admin/audit',
    icon: History,
  },
  {
    name: 'Settings',
    href: '/admin/settings',
    icon: Settings,
  },
]

// Role display labels
const roleLabels: Record<string, string> = {
  SUPER_ADMIN: 'Super Admin',
  PROGRAM_ADMIN: 'Program Admin',
  JURY_MEMBER: 'Jury Member',
  OBSERVER: 'Observer',
}

export function AdminSidebar({ user }: AdminSidebarProps) {
  const pathname = usePathname()
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false)
  const { status: sessionStatus } = useSession()
  const isAuthenticated = sessionStatus === 'authenticated'
  const { data: avatarUrl } = trpc.avatar.getUrl.useQuery(undefined, {
    enabled: isAuthenticated,
  })
  const { currentEdition } = useEdition()

  const isSuperAdmin = user.role === 'SUPER_ADMIN'
  const roleLabel = roleLabels[user.role || ''] || 'User'

  // Build dynamic admin nav with current edition's apply page
  const dynamicAdminNav = adminNavigation.map((item) => {
    if (item.name === 'Apply Page' && currentEdition?.id) {
      return { ...item, href: `/admin/programs/${currentEdition.id}/apply-settings` }
    }
    return item
  })

  return (
    <>
      {/* Mobile menu button */}
      <div className="fixed top-0 left-0 right-0 z-40 flex h-16 items-center justify-between border-b bg-card px-4 lg:hidden overflow-x-hidden">
        <Logo showText textSuffix="Admin" className="min-w-0" />
        <div className="flex items-center gap-2">
          <NotificationBell />
          <Button
            variant="ghost"
            size="icon"
            aria-label={isMobileMenuOpen ? 'Close menu' : 'Open menu'}
            onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
          >
            {isMobileMenuOpen ? (
              <X className="h-5 w-5" />
            ) : (
              <Menu className="h-5 w-5" />
            )}
          </Button>
        </div>
      </div>

      {/* Mobile menu overlay */}
      {isMobileMenuOpen && (
        <div
          className="fixed inset-0 z-30 bg-black/50 lg:hidden"
          onClick={() => setIsMobileMenuOpen(false)}
        />
      )}

      {/* Sidebar */}
      <aside
        className={cn(
          'fixed inset-y-0 left-0 z-40 flex w-64 flex-col border-r bg-card transition-transform duration-300 lg:translate-x-0',
          isMobileMenuOpen ? 'translate-x-0' : '-translate-x-full'
        )}
      >
        {/* Logo + Notification */}
        <div className="flex h-16 items-center justify-between border-b px-6">
          <Logo showText textSuffix="Admin" />
          <div className="hidden lg:flex items-center gap-1">
            <NotificationBell />
          </div>
        </div>

        {/* Edition Selector */}
        <div className="border-b px-4 py-4">
          <EditionSelector />
        </div>

        {/* Navigation */}
        <nav className="flex-1 space-y-1 overflow-y-auto px-3 py-4">
          <div className="space-y-1">
            {navigation.map((item) => {
              const isActive =
                pathname === item.href ||
                (item.href !== '/admin' && pathname.startsWith(item.href))
              const isParentActive = item.subItems
                ? pathname.startsWith('/admin/rounds')
                : false
              return (
                <div key={item.name}>
                  <Link
                    href={item.href as Route}
                    onClick={() => setIsMobileMenuOpen(false)}
                    className={cn(
                      'group flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-150',
                      isActive
                        ? 'bg-brand-blue text-white shadow-xs'
                        : 'text-muted-foreground hover:bg-muted hover:text-foreground'
                    )}
                  >
                    <item.icon className={cn(
                      'h-4 w-4 transition-colors',
                      isActive ? 'text-white' : 'text-muted-foreground group-hover:text-foreground'
                    )} />
                    {item.name}
                  </Link>
                  {item.subItems && isParentActive && (
                    <div className="ml-7 mt-0.5 space-y-0.5">
                      {item.subItems.map((sub) => {
                        const isSubActive = pathname === sub.href ||
                          (sub.href !== '/admin/rounds' && pathname.startsWith(sub.href))
                        return (
                          <Link
                            key={sub.name}
                            href={sub.href as Route}
                            onClick={() => setIsMobileMenuOpen(false)}
                            className={cn(
                              'block rounded-md px-3 py-1.5 text-xs font-medium transition-colors',
                              isSubActive
                                ? 'text-brand-blue bg-brand-blue/10'
                                : 'text-muted-foreground hover:text-foreground hover:bg-muted'
                            )}
                          >
                            {sub.name}
                          </Link>
                        )
                      })}
                    </div>
                  )}
                </div>
              )
            })}
          </div>

          {isSuperAdmin && (
            <>
              <Separator className="my-4" />
              <div className="space-y-1">
                <p className="mb-2 px-3 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/60">
                  Administration
                </p>
                {dynamicAdminNav.map((item) => {
                  let isActive = pathname.startsWith(item.href)
                  if (item.activeMatch) {
                    isActive = pathname.includes(item.activeMatch)
                  } else if (item.activeExclude && pathname.includes(item.activeExclude)) {
                    isActive = false
                  }
                  return (
                    <Link
                      key={item.name}
                      href={item.href as Route}
                      onClick={() => setIsMobileMenuOpen(false)}
                      className={cn(
                        'group flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-150',
                        isActive
                          ? 'bg-brand-blue text-white shadow-xs'
                          : 'text-muted-foreground hover:bg-muted hover:text-foreground'
                      )}
                    >
                      <item.icon className={cn(
                        'h-4 w-4 transition-colors',
                        isActive ? 'text-white' : 'text-muted-foreground group-hover:text-foreground'
                      )} />
                      {item.name}
                    </Link>
                  )
                })}
              </div>
            </>
          )}
        </nav>

        {/* User Profile Section */}
        <div className="border-t p-3">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <button className="group flex w-full items-center gap-3 rounded-xl p-2.5 text-left transition-all duration-200 hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
                {/* Avatar */}
                <div className="relative shrink-0">
                  <UserAvatar user={user} avatarUrl={avatarUrl} size="md" />
                  {/* Online indicator */}
                  <div className="absolute -bottom-0.5 -right-0.5 h-3 w-3 rounded-full border-2 border-background bg-emerald-500" />
                </div>

                {/* User info */}
                <div className="min-w-0 flex-1">
                  <p className="truncate text-sm font-semibold text-foreground">
                    {user.name || 'User'}
                  </p>
                  <p className="truncate text-xs text-muted-foreground">
                    {roleLabel}
                  </p>
                </div>

                {/* Chevron */}
                <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200 group-hover:translate-x-0.5 group-hover:text-foreground" />
              </button>
            </DropdownMenuTrigger>

            <DropdownMenuContent
              align="end"
              side="top"
              sideOffset={8}
              className="w-56 p-1.5"
            >
              {/* User info header */}
              <div className="px-2 py-2.5">
                <p className="text-sm font-semibold text-foreground">
                  {user.name || 'User'}
                </p>
                <p className="truncate text-xs text-muted-foreground">
                  {user.email}
                </p>
              </div>

              <DropdownMenuSeparator className="my-1" />

              <DropdownMenuItem asChild>
                <Link
                  href={"/settings/profile" as Route}
                  className="flex cursor-pointer items-center gap-2.5 rounded-md px-2 py-2"
                >
                  <User className="h-4 w-4 text-muted-foreground" />
                  <span>Profile Settings</span>
                </Link>
              </DropdownMenuItem>

              <DropdownMenuSeparator className="my-1" />

              <DropdownMenuItem
                onClick={() => signOut({ callbackUrl: '/login' })}
                className="flex cursor-pointer items-center gap-2.5 rounded-md px-2 py-2 text-destructive focus:bg-destructive/10 focus:text-destructive"
              >
                <LogOut className="h-4 w-4" />
                <span>Sign Out</span>
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </aside>
    </>
  )
}
