import { LayoutDashboard, FileText, Flag, Users, Settings, ArrowLeft, ScrollText, BookOpen, Inbox, Mail, AlertTriangle, Shield, Activity } from 'lucide-react';
import { NavLink } from 'react-router-dom';
import { useUserRole } from '@/hooks/useUserRole';
import { useSidebar } from '@/hooks/useSidebar';
import { useCombinedAlerts } from '@/hooks/admin/useCombinedAlerts';
import { Badge } from '@/components/ui/badge';
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
} from '@/components/ui/sidebar';

export function AdminSidebar() {
  const { state } = useSidebar();
  const { permissions } = useUserRole();
  const isSuperuser = permissions?.role_level === 'superuser';
  const isAdmin = permissions?.role_level === 'admin' || isSuperuser;
  const collapsed = state === 'collapsed';
  const { data: combinedAlerts } = useCombinedAlerts();
  const alertCount = combinedAlerts?.length || 0;

  const navItems = [
    {
      title: 'Dashboard',
      url: '/admin',
      icon: LayoutDashboard,
    },
    {
      title: 'Monitoring Overview',
      url: '/admin/monitoring-overview',
      icon: Activity,
      badge: alertCount > 0 ? alertCount : undefined,
    },
    {
      title: 'Moderation',
      url: '/admin/moderation',
      icon: FileText,
    },
    {
      title: 'Reports',
      url: '/admin/reports',
      icon: Flag,
    },
    {
      title: 'Inbox',
      url: '/admin/contact',
      icon: Inbox,
    },
    {
      title: 'System Log',
      url: '/admin/system-log',
      icon: ScrollText,
    },
    {
      title: 'Monitoring & Logs',
      url: '/admin/error-monitoring',
      icon: AlertTriangle,
    },
    {
      title: 'Rate Limit Metrics',
      url: '/admin/rate-limit-metrics',
      icon: Shield,
    },
    {
      title: 'Users',
      url: '/admin/users',
      icon: Users,
    },
    ...(isAdmin ? [{
      title: 'Blog',
      url: '/admin/blog',
      icon: BookOpen,
    }] : []),
    ...(isSuperuser ? [{
      title: 'Settings',
      url: '/admin/settings',
      icon: Settings,
    }, {
      title: 'Email Settings',
      url: '/admin/email-settings',
      icon: Mail,
    }] : []),
  ];

  return (
    <Sidebar collapsible="icon">
      <SidebarHeader className="border-b border-border/40 px-4 py-4">
        <div className="flex items-center gap-2 min-h-[32px]">
          <div className="flex items-center justify-center flex-shrink-0">
            <img 
              src="https://cdn.thrillwiki.com/images/5d06b122-a3a3-47bc-6176-f93ad8f0ce00/favicon512" 
              alt="ThrillWiki" 
              width="32"
              height="32"
              loading="eager"
              decoding="async"
              draggable="false"
              className={`
                object-contain
                transition-all duration-200 ease-in-out
                ${collapsed ? 'w-6 h-6' : 'w-8 h-8'}
              `}
              onError={(e) => {
                const img = e.target as HTMLImageElement;
                if (!img.src.includes('favicon128')) {
                  img.src = 'https://cdn.thrillwiki.com/images/5d06b122-a3a3-47bc-6176-f93ad8f0ce00/favicon128';
                }
              }}
            />
          </div>
          {!collapsed && (
            <div className="flex flex-col overflow-hidden">
              <span className="text-sm font-semibold truncate">ThrillWiki</span>
              <span className="text-xs text-muted-foreground truncate">Admin Panel</span>
            </div>
          )}
        </div>
      </SidebarHeader>

      <SidebarContent>
        <SidebarGroup>
          <SidebarGroupLabel>Navigation</SidebarGroupLabel>
          <SidebarGroupContent>
            <SidebarMenu>
              {navItems.map((item) => (
                <SidebarMenuItem key={item.url}>
                  <SidebarMenuButton asChild tooltip={collapsed ? item.title : undefined}>
                    <NavLink
                      to={item.url}
                      end={item.url === '/admin'}
                      className={({ isActive }) =>
                        isActive
                          ? 'bg-sidebar-accent text-sidebar-accent-foreground font-medium'
                          : 'hover:bg-sidebar-accent/50 hover:text-sidebar-accent-foreground'
                      }
                    >
                      <item.icon className="w-4 h-4" />
                      {!collapsed && (
                        <span className="flex items-center gap-2">
                          {item.title}
                          {item.badge !== undefined && (
                            <Badge variant="destructive" className="text-xs h-5 px-1.5">
                              {item.badge}
                            </Badge>
                          )}
                        </span>
                      )}
                      {collapsed && item.badge !== undefined && item.badge > 0 && (
                        <Badge variant="destructive" className="text-xs h-5 w-5 p-0 flex items-center justify-center absolute -top-1 -right-1">
                          {item.badge}
                        </Badge>
                      )}
                    </NavLink>
                  </SidebarMenuButton>
                </SidebarMenuItem>
              ))}
            </SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>
      </SidebarContent>

      <SidebarFooter className="border-t border-border/40">
        <SidebarMenu>
          <SidebarMenuItem>
            <SidebarMenuButton asChild tooltip={collapsed ? 'Back to ThrillWiki' : undefined}>
              <NavLink to="/" className="hover:bg-sidebar-accent/50 hover:text-sidebar-accent-foreground">
                <ArrowLeft className="w-4 h-4" />
                {!collapsed && <span>Back to ThrillWiki</span>}
              </NavLink>
            </SidebarMenuButton>
          </SidebarMenuItem>
        </SidebarMenu>
      </SidebarFooter>
    </Sidebar>
  );
}
