import { useState, useEffect } from 'react';
import { 
  ChevronDown, 
  ChevronRight, 
  ChevronsLeft, 
  ChevronsRight,
  FolderOpen,
  UserCircle,
  Gauge,
  MonitorDot,
  AlertTriangle,
  Target,
  BarChart3,
  CalendarClock,
  Shield,
  FileText,
  Map,
  TrendingUp,
  CloudSun,
  ClipboardCheck,
  GitCompare,
  AlertCircle,
  ClipboardList,
  ListTodo,
  PlayCircle,
  Calendar,
  Archive,
  BookOpen,
  Award,
  MessageSquare,
  Database,
  ShoppingCart,
  Package,
  HandCoins,
  Undo2,
  Wrench,
  PieChart,
  Radar,
  Blocks,
  Cpu,
  Lightbulb,
  Brain,
  Zap,
  Library,
  Eye,
  Settings,
  Droplets,
  FlaskConical,
  Sliders,
  Bell,
  Building2,
  Users,
  Cog,
  Activity,
  Mail,
  LucideIcon,
} from 'lucide-react';
import { MenuItem } from '../types/navigation';
import { cn } from './ui/utils';
import { Button } from './ui/button';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './ui/tooltip';

interface SidebarProps {
  menus: MenuItem[];
  activePath: string;
  onNavigate: (path: string) => void;
  collapsed?: boolean;
  onCollapsedChange?: (collapsed: boolean) => void;
}

export function Sidebar({ menus, activePath, onNavigate, collapsed = false, onCollapsedChange }: SidebarProps) {
  // 图标映射
  const iconMap: Record<string, LucideIcon> = {
    FolderOpen,
    UserCircle,
    Gauge,
    MonitorDot,
    AlertTriangle,
    Target,
    BarChart3,
    CalendarClock,
    Shield,
    FileText,
    Map,
    TrendingUp,
    CloudSun,
    ClipboardCheck,
    GitCompare,
    AlertCircle,
    ClipboardList,
    ListTodo,
    PlayCircle,
    Calendar,
    Archive,
    BookOpen,
    Award,
    MessageSquare,
    Database,
    ShoppingCart,
    Package,
    HandCoins,
    Undo2,
    Wrench,
    PieChart,
    Radar,
    Blocks,
    Cpu,
    Lightbulb,
    Brain,
    Zap,
    Library,
    Eye,
    Settings,
    Droplets,
    FlaskConical,
    Sliders,
    Bell,
    Building2,
    Users,
    Cog,
    Activity,
    Mail,
  };

  // 获取图标组件
  const getIcon = (iconName?: string) => {
    if (!iconName) return null;
    const IconComponent = iconMap[iconName];
    return IconComponent ? <IconComponent className="w-4 h-4" /> : null;
  };

  // 根据activePath自动展开包含该路径的菜单
  const getInitialExpandedMenus = () => {
    const expanded = new Set<string>();
    menus.forEach(menu => {
      if (menu.children?.some(child => child.path === activePath)) {
        expanded.add(menu.id);
      }
    });
    // 如果没有匹配的，默认展开第一个
    if (expanded.size === 0 && menus.length > 0) {
      expanded.add(menus[0].id);
    }
    return expanded;
  };

  const [expandedMenus, setExpandedMenus] = useState<Set<string>>(getInitialExpandedMenus());

  // 当activePath或menus变化时，自动展开对应的菜单
  useEffect(() => {
    menus.forEach(menu => {
      if (menu.children?.some(child => child.path === activePath)) {
        setExpandedMenus(prev => {
          const newSet = new Set(prev);
          newSet.add(menu.id);
          return newSet;
        });
      }
    });
  }, [activePath, menus]);

  const toggleMenu = (menuId: string) => {
    setExpandedMenus(prev => {
      const newSet = new Set(prev);
      if (newSet.has(menuId)) {
        newSet.delete(menuId);
      } else {
        newSet.add(menuId);
      }
      return newSet;
    });
  };

  return (
    <div 
      className={cn(
        "bg-card border-r border-border overflow-y-auto transition-all duration-300 flex flex-col",
        collapsed ? "w-16" : "w-64"
      )}
    >
      {/* 菜单内容 */}
      <div className="flex-1 overflow-y-auto p-4">
        <nav className="space-y-1">
          {menus.map((menu) => (
            <div key={menu.id}>
              {/* 一级菜单 */}
              {collapsed ? (
                <TooltipProvider delayDuration={0}>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <button
                        onClick={() => {
                          if (menu.children && menu.children.length > 0) {
                            // 收起状态下点击一级菜单，导航到第一个子菜单
                            onNavigate(menu.children[0].path);
                          }
                        }}
                        className={cn(
                          "w-full flex items-center justify-center px-2 py-2.5 rounded-md transition-colors",
                          "hover:bg-accent hover:text-primary",
                          menu.children?.some(child => child.path === activePath) 
                            ? "bg-primary/10 text-primary" 
                            : "text-muted-foreground"
                        )}
                      >
                        {getIcon(menu.icon)}
                      </button>
                    </TooltipTrigger>
                    <TooltipContent side="right" className="max-w-xs">
                      <div className="space-y-1">
                        <p className="text-sm">{menu.label}</p>
                        {menu.children && (
                          <div className="text-xs text-muted-foreground mt-2 space-y-1">
                            {menu.children.map((child) => (
                              <div key={child.id}>{child.label}</div>
                            ))}
                          </div>
                        )}
                      </div>
                    </TooltipContent>
                  </Tooltip>
                </TooltipProvider>
              ) : (
                <button
                  onClick={() => toggleMenu(menu.id)}
                  className={cn(
                    "w-full flex items-center gap-3 px-3 py-2 rounded-md transition-colors text-sm",
                    "hover:bg-accent group"
                  )}
                >
                  <span className={cn(
                    "transition-colors",
                    menu.children?.some(child => child.path === activePath)
                      ? "text-primary"
                      : "text-muted-foreground group-hover:text-primary"
                  )}>
                    {getIcon(menu.icon)}
                  </span>
                  <span className="flex-1 text-left text-foreground">{menu.label}</span>
                  {menu.children && (
                    expandedMenus.has(menu.id) ? (
                      <ChevronDown className="w-4 h-4 text-muted-foreground flex-shrink-0" />
                    ) : (
                      <ChevronRight className="w-4 h-4 text-muted-foreground flex-shrink-0" />
                    )
                  )}
                </button>
              )}

              {/* 二级菜单 - 仅在展开状态显示 */}
              {!collapsed && menu.children && expandedMenus.has(menu.id) && (
                <div className="ml-4 mt-1 space-y-1">
                  {menu.children.map((child) => (
                    <button
                      key={child.id}
                      onClick={() => child.path && onNavigate(child.path)}
                      className={cn(
                        "w-full text-left px-3 py-1.5 rounded-md transition-colors text-xs",
                        activePath === child.path
                          ? "bg-primary/10 text-primary font-medium"
                          : "text-muted-foreground hover:bg-accent hover:text-foreground"
                      )}
                    >
                      {child.label}
                    </button>
                  ))}
                </div>
              )}
            </div>
          ))}
        </nav>
      </div>
    </div>
  );
}
