import { useState } from "react";
import { Link, useLocation } from "wouter";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { useAuth } from "@/hooks/useAuth";
import { useSport } from "@/hooks/useSport";
import { 
  Users, 
  UserPlus, 
  Award, 
  Settings, 
  Search,
  Shield,
  Trophy,
  DollarSign,
  Calendar,
  Activity,
  ArrowUpDown,
  FileText,
  CreditCard,
  MessageSquare,
  HelpCircle,
  PlayCircle,
  Layout,
  User,
  Server,
  Bug,
  ChevronLeft,
  ChevronRight,
  Palette,
  Presentation,
  Bell,
  TrendingUp,
  ScrollText,
  MapPin,
  ArrowRightLeft,
  Home,
  Sparkles
} from "lucide-react";

interface SidebarProps {
  isOpen?: boolean;
  isCollapsed?: boolean;
  onToggle?: () => void;
  onClose?: () => void;
}

const navigationItems = [
  { path: "/", label: "Dashboard", icon: Home, category: "main", badge: null, tourId: null },
  { path: "/notifications", label: "Notifications", icon: Bell, category: "main", badge: "3", tourId: null },

  { path: "/teams", label: "Teams", icon: Users, category: "management", badge: null, tourId: "teams-overview" },
  { path: "/players", label: "Players", icon: UserPlus, category: "management", badge: null, tourId: "players-overview" },
  { path: "/coaches", label: "Coaches", icon: Award, category: "management", badge: null, tourId: null },
  { path: "/roster", label: "Roster", icon: ArrowUpDown, category: "management", badge: null },
  { path: "/subscriptions", label: "Subscriptions", icon: CreditCard, category: "management", badge: null },
  { path: "/payments", label: "Payments", icon: DollarSign, category: "management", badge: null },

  { path: "/leagues", label: "Leagues", icon: Trophy, category: "operations", badge: null },
  { path: "/fixtures", label: "Fixtures", icon: Calendar, category: "operations", badge: null },
  { path: "/venues", label: "Venues", icon: MapPin, category: "operations", badge: null },
  { path: "/transfers", label: "Transfers", icon: ArrowRightLeft, category: "operations", badge: null },
  { path: "/training", label: "Training", icon: Activity, category: "operations", badge: null },
  { path: "/coaching-feedback", label: "Feedback", icon: MessageSquare, category: "operations", badge: null },
  { path: "/tournaments", label: "Tournaments", icon: Trophy, category: "operations", badge: null },

  { path: "/reports", label: "Reports", icon: TrendingUp, category: "analytics", badge: null },
  { path: "/audit-logs", label: "Audit Logs", icon: ScrollText, category: "analytics", badge: null },

  { path: "/profile", label: "Profile", icon: User, category: "user", badge: null },
  { path: "/settings", label: "Settings", icon: Settings, category: "user", badge: null },

  { path: "/admin", label: "User Management", icon: Shield, category: "admin", badge: null },
  { path: "/language-settings", label: "Language", icon: Settings, category: "admin", badge: null },
  { path: "/security", label: "Security", icon: Shield, category: "admin", badge: null },
  { path: "/branding-settings", label: "Branding", icon: Palette, category: "admin", badge: null },
  { path: "/theme-settings", label: "Themes", icon: Palette, category: "admin", badge: null },
  { path: "/form-builder", label: "Forms", icon: FileText, category: "admin", badge: null },
  { path: "/payment-gateways", label: "Gateways", icon: CreditCard, category: "admin", badge: null },

  { path: "/superadmin", label: "Super Admin", icon: Shield, category: "superadmin", badge: null },
  { path: "/module-management", label: "Modules", icon: Layout, category: "superadmin", badge: null },
  { path: "/cpanel-installation", label: "cPanel", icon: Server, category: "superadmin", badge: null },
  { path: "/system-debug", label: "Debug", icon: Bug, category: "superadmin", badge: null },
  { path: "/proposal", label: "Proposal", icon: Presentation, category: "superadmin", badge: null },

  { path: "/onboarding", label: "Take Tour", icon: PlayCircle, category: "help", badge: null },
  { path: "/help", label: "Help", icon: HelpCircle, category: "help", badge: null },
];

const NavItem = ({ item, isActive, isCollapsed }: { item: typeof navigationItems[0], isActive: boolean, isCollapsed: boolean }) => {
  const Icon = item.icon;
  
  return (
    <Link to={item.path}>
      <Button
        variant="ghost"
        className={cn(
          "w-full justify-start transition-all duration-200 group relative",
          isCollapsed ? "px-0 h-11" : "px-3 h-10",
          isActive 
            ? "bg-gradient-to-r from-blue-600 to-purple-600 text-white hover:from-blue-700 hover:to-purple-700 shadow-lg" 
            : "text-slate-300 hover:text-white hover:bg-slate-800/60"
        )}
        data-testid={`nav-${item.path.replace('/', '')}`}
        aria-label={isCollapsed ? item.label : undefined}
      >
        <div className={cn(
          "flex items-center gap-3 w-full",
          isCollapsed && "justify-center"
        )}>
          <Icon className={cn(
            "h-5 w-5 shrink-0 transition-transform group-hover:scale-110",
            isActive ? "text-white" : "text-slate-400"
          )} />
          {!isCollapsed && (
            <>
              <span className="text-sm font-medium truncate flex-1 text-left">{item.label}</span>
              {item.badge && (
                <Badge variant="secondary" className="h-5 min-w-5 flex items-center justify-center px-1.5 text-[10px] font-bold bg-blue-500 text-white border-0">
                  {item.badge}
                </Badge>
              )}
            </>
          )}
        </div>
        {isActive && !isCollapsed && (
          <div className="absolute right-0 top-1/2 -translate-y-1/2 w-1 h-6 bg-white rounded-l-full" />
        )}
      </Button>
    </Link>
  );
};

export default function Sidebar({ isOpen = true, isCollapsed = false, onToggle }: SidebarProps) {
  const [location] = useLocation();
  const [searchQuery, setSearchQuery] = useState("");
  const { user } = useAuth();
  const { isTeamSport } = useSport();

  const isAdmin = (user as any)?.role === 'admin' || (user as any)?.role === 'superadmin';
  const isSuperAdmin = (user as any)?.role === 'superadmin';

  // Filter navigation based on sport type
  const getSportSpecificNavigation = () => {
    if (!isTeamSport) {
      return navigationItems.filter(item => 
        !['teams', 'roster', 'coaching-feedback'].some(excluded => item.path.includes(excluded))
      );
    }
    return navigationItems;
  };

  const sportSpecificNavigation = getSportSpecificNavigation();

  // Filter based on search
  const filteredNavigation = sportSpecificNavigation.filter(item =>
    item.label.toLowerCase().includes(searchQuery.toLowerCase())
  );

  if (!isOpen) return null;

  const renderSection = (title: string, category: string, icon?: any) => {
    const items = filteredNavigation.filter(item => item.category === category);
    if (items.length === 0) return null;

    const SectionIcon = icon;

    return (
      <div className="mb-6">
        {!isCollapsed && (
          <div className="px-3 mb-2.5 flex items-center gap-2">
            {SectionIcon && <SectionIcon className="h-3.5 w-3.5 text-slate-500" />}
            <h3 className="text-[11px] font-bold uppercase tracking-wider text-slate-400">
              {title}
            </h3>
          </div>
        )}
        {isCollapsed && items.length > 0 && (
          <div className="h-px bg-slate-700/50 mb-2 mx-4" />
        )}
        <div className="space-y-1">
          {items.map((item) => (
            <NavItem
              key={item.path}
              item={item}
              isActive={location === item.path}
              isCollapsed={isCollapsed}
            />
          ))}
        </div>
      </div>
    );
  };

  return (
    <aside 
      className={cn(
        "fixed left-0 top-0 h-full bg-slate-900 dark:bg-slate-950 border-r border-slate-700/50 dark:border-slate-800/50 flex flex-col z-50 overflow-hidden transition-all duration-300 ease-in-out shadow-2xl",
        isCollapsed ? "w-[72px]" : "w-64"
      )} 
      data-tour="sidebar"
    >
      {/* Header */}
      <div className="h-[73px] flex items-center justify-between border-b border-slate-700/50 dark:border-slate-800/50 px-4 bg-slate-800/60 dark:bg-slate-900/60 backdrop-blur-sm">
        {!isCollapsed ? (
          <>
            <div className="flex items-center gap-3">
              <div className="relative group">
                <div className="absolute inset-0 bg-gradient-to-br from-blue-500 to-purple-600 rounded-lg blur-sm opacity-50 group-hover:opacity-70 transition-opacity"></div>
                <div className="relative w-9 h-9 bg-gradient-to-br from-blue-500 to-purple-600 rounded-lg flex items-center justify-center shadow-lg">
                  <Trophy className="text-white w-5 h-5" />
                </div>
              </div>
              <div>
                <h1 className="text-base font-bold text-white tracking-tight">SportsPro</h1>
                <p className="text-[10px] font-medium text-slate-400 tracking-wide">MANAGEMENT</p>
              </div>
            </div>
            <Button
              variant="ghost"
              size="sm"
              onClick={onToggle}
              className="h-8 w-8 p-0 rounded-lg hover:bg-slate-700/50 text-slate-300 hover:text-white transition-all hover:scale-105"
              data-testid="button-collapse-sidebar"
              aria-label="Collapse sidebar"
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
          </>
        ) : (
          <div className="w-full flex flex-col items-center gap-2">
            <div className="relative group">
              <div className="absolute inset-0 bg-gradient-to-br from-blue-500 to-purple-600 rounded-lg blur-sm opacity-50 group-hover:opacity-70 transition-opacity"></div>
              <div className="relative w-9 h-9 bg-gradient-to-br from-blue-500 to-purple-600 rounded-lg flex items-center justify-center shadow-lg">
                <Trophy className="text-white w-5 h-5" />
              </div>
            </div>
            <Button
              variant="ghost"
              size="sm"
              onClick={onToggle}
              className="h-7 w-7 p-0 rounded-lg hover:bg-slate-700/50 text-slate-300 hover:text-white transition-all hover:scale-105"
              data-testid="button-expand-sidebar"
              aria-label="Expand sidebar"
            >
              <ChevronRight className="h-3.5 w-3.5" />
            </Button>
          </div>
        )}
      </div>

      {/* Scrollable Content */}
      <div className={cn(
        "flex-1 overflow-y-auto px-3 py-4 scrollbar-thin scrollbar-thumb-slate-600 scrollbar-track-transparent",
        isCollapsed && "px-2"
      )}>
        {/* Search */}
        {!isCollapsed && (
          <div className="mb-6">
            <div className="relative group">
              <Search className="absolute left-3 top-2.5 h-4 w-4 text-slate-400 transition-colors group-focus-within:text-blue-400" />
              <Input
                type="text"
                placeholder="Search navigation..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-9 h-10 bg-slate-800/50 border-slate-700/50 text-white placeholder:text-slate-500 focus:bg-slate-800 focus:border-blue-500/50 focus:ring-1 focus:ring-blue-500/30 transition-all"
                data-testid="input-search"
              />
            </div>
          </div>
        )}

        {isCollapsed && (
          <div className="mb-4 flex justify-center">
            <Button
              variant="ghost"
              size="sm"
              className="h-11 w-11 p-0 rounded-lg hover:bg-slate-800/60 text-slate-400 hover:text-white transition-all hover:scale-105"
              aria-label="Search navigation"
            >
              <Search className="h-5 w-5" />
            </Button>
          </div>
        )}

        {/* Navigation Sections */}
        <nav className="space-y-6">
          {renderSection("Overview", "main", Sparkles)}
          {renderSection("Team Management", "management", Users)}
          {renderSection("Operations", "operations", Activity)}
          {renderSection("Analytics & Reports", "analytics", TrendingUp)}
          {renderSection("My Account", "user", User)}
          {isAdmin && renderSection("Administration", "admin", Shield)}
          {isSuperAdmin && renderSection("Super Admin", "superadmin", Shield)}
          {renderSection("Support", "help", HelpCircle)}
        </nav>
      </div>

      {/* Footer */}
      {!isCollapsed && (
        <div className="border-t border-slate-700/50 p-4 bg-slate-800/60 backdrop-blur-sm">
          <div className="flex items-center justify-between px-2">
            <div>
              <p className="text-xs font-bold text-slate-300">Version 2.0.0</p>
              <p className="text-[10px] text-slate-500">© 2025 SportsPro</p>
            </div>
            <Badge variant="outline" className="text-[10px] font-semibold border-blue-500/50 text-blue-400">
              PRO
            </Badge>
          </div>
        </div>
      )}
    </aside>
  );
}
