'use client'

import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { useSession } from 'next-auth/react'
import { cn } from '@/lib/utils'
import { hasPermission, Permission } from '@/lib/services/permission-service'
import { StaffRole } from '@prisma/client'
import {
  LayoutDashboard,
  Users,
  ShoppingCart,
  BarChart3,
  Settings,
  LogOut,
  Server,
  Cloud,
  Building2,
  UserCog,
  User,
} from 'lucide-react'
import { signOut } from 'next-auth/react'
import { Button } from '@/components/ui/button'

interface NavItem {
  name: string
  href: string
  icon: typeof LayoutDashboard
  permission?: Permission
}

const navigation: NavItem[] = [
  {
    name: 'Dashboard',
    href: '/admin',
    icon: LayoutDashboard,
    permission: 'dashboard:view',
  },
  {
    name: 'Orders',
    href: '/admin/orders',
    icon: ShoppingCart,
    permission: 'orders:view',
  },
  {
    name: 'Customers',
    href: '/admin/customers',
    icon: Users,
    permission: 'customers:view',
  },
  {
    name: 'Servers',
    href: '/admin/servers',
    icon: Server,
    permission: 'servers:view',
  },
  {
    name: 'Netcup',
    href: '/admin/servers/netcup',
    icon: Cloud,
    permission: 'servers:view',
  },
  {
    name: 'Enterprise Clients',
    href: '/admin/enterprise-clients',
    icon: Building2,
    permission: 'enterprise:view',
  },
  {
    name: 'Staff',
    href: '/admin/staff',
    icon: UserCog,
    permission: 'staff:view',
  },
  {
    name: 'Analytics',
    href: '/admin/analytics',
    icon: BarChart3,
    permission: 'dashboard:view',
  },
  {
    name: 'Settings',
    href: '/admin/settings',
    icon: Settings,
    permission: 'settings:view',
  },
]

export function AdminSidebar() {
  const pathname = usePathname()
  const { data: session } = useSession()
  const userRole = (session?.user?.role as StaffRole) || 'SUPPORT'

  // Filter navigation items based on permissions
  const visibleNavigation = navigation.filter((item) => {
    if (!item.permission) return true
    return hasPermission(userRole, item.permission)
  })

  return (
    <div className="flex h-full w-64 flex-col bg-gray-900">
      {/* Logo */}
      <div className="flex h-16 items-center px-6">
        <Link href="/admin" className="flex items-center gap-2">
          <div className="h-8 w-8 rounded-lg bg-primary flex items-center justify-center">
            <span className="text-primary-foreground font-bold text-sm">LB</span>
          </div>
          <span className="text-xl font-bold text-white">LetsBe Hub</span>
        </Link>
      </div>

      {/* Navigation */}
      <nav className="flex-1 space-y-1 px-3 py-4">
        {visibleNavigation.map((item) => {
          // Check if this item is active
          // For exact matches, always active
          // For prefix matches, only active if no more specific nav item matches
          const isExactMatch = pathname === item.href
          const isPrefixMatch = item.href !== '/admin' && pathname.startsWith(item.href)
          const hasMoreSpecificNav = visibleNavigation.some(
            (other) =>
              other.href !== item.href &&
              other.href.length > item.href.length &&
              pathname.startsWith(other.href)
          )
          const isActive = isExactMatch || (isPrefixMatch && !hasMoreSpecificNav)

          return (
            <Link
              key={item.name}
              href={item.href}
              className={cn(
                'group flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors',
                isActive
                  ? 'bg-gray-800 text-white'
                  : 'text-gray-400 hover:bg-gray-800 hover:text-white'
              )}
            >
              <item.icon
                className={cn(
                  'h-5 w-5 shrink-0',
                  isActive ? 'text-primary' : 'text-gray-400 group-hover:text-white'
                )}
              />
              {item.name}
            </Link>
          )
        })}
      </nav>

      {/* User section */}
      <div className="border-t border-gray-800 p-4 space-y-1">
        <Link
          href="/admin/profile"
          className={cn(
            'group flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors',
            pathname === '/admin/profile'
              ? 'bg-gray-800 text-white'
              : 'text-gray-400 hover:bg-gray-800 hover:text-white'
          )}
        >
          <User className={cn(
            'h-5 w-5 shrink-0',
            pathname === '/admin/profile' ? 'text-primary' : 'text-gray-400 group-hover:text-white'
          )} />
          My Profile
        </Link>
        <Button
          variant="ghost"
          className="w-full justify-start gap-3 text-gray-400 hover:bg-gray-800 hover:text-white"
          onClick={() => signOut({ callbackUrl: '/login' })}
        >
          <LogOut className="h-5 w-5" />
          Sign Out
        </Button>
      </div>
    </div>
  )
}
