'use client';

import { useState, useEffect } from 'react';
import { ChevronDown, ChevronLeft, ChevronRight, Menu, X } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from '@/components/ui/collapsible';

interface MenuItem {
  id: string;
  label: string;
  icon?: React.ReactNode;
  children?: {
    id: string;
    label: string;
    path?: string;
  }[];
}

interface LeftSidebarProps {
  menus: MenuItem[];
  activePath: string;
  onNavigate: (path: string) => void;
  isMobile?: boolean;
  isCollapsed?: boolean;
  onToggleCollapse?: () => void;
}

export function LeftSidebar({
  menus,
  activePath,
  onNavigate,
  isMobile = false,
  isCollapsed = false,
  onToggleCollapse
}: LeftSidebarProps) {
  // 初始状态下所有菜单都折叠
  const getInitialExpandedMenus = () => {
    return new Set<string>();
  };

  // 检查菜单是否有子菜单被选中或是否应该高亮
  const isMenuActive = (menu: MenuItem) => {
    // 检查是否有子菜单被选中
    if (menu.children?.some(child => child.path === activePath)) {
      return true;
    }
    // 如果当前路径匹配菜单的URL（无子菜单的情况）
    if (activePath && activePath.includes(menu.id)) {
      return true;
    }
    return false;
  };

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

  // 不自动展开菜单，由用户手动控制

  // 当侧边栏状态改变时，折叠所有菜单
  useEffect(() => {
    setExpandedMenus(new Set());
  }, [isCollapsed]);

  return (
    <div
      className={cn(
        "bg-background border-r transition-all duration-300 flex flex-col h-full",
        isMobile ? "fixed inset-y-0 left-0 z-50" : "relative",
        isCollapsed ? "w-16" : "w-64"
      )}
    >
      {/* 头部 - 缩小高度 */}
      <div className="px-2 py-1 border-b">
        <div className="flex items-center justify-between">
          <h2 className={cn(
            "font-medium text-sm transition-all duration-300",
            isCollapsed ? "hidden" : "block"
          )}>
            导航菜单
          </h2>
          {isMobile ? (
            <Button variant="ghost" size="icon" className="h-8 w-8">
              <X className="w-4 h-4" />
            </Button>
          ) : (
            /* 根据侧边栏状态显示不同按钮 */
            <Button
              variant="ghost"
              size="icon"
              onClick={onToggleCollapse}
              className="h-8 w-8"
              title={isCollapsed ? "展开菜单" : "收起菜单"}
            >
              {isCollapsed ? (
                <ChevronRight className="w-4 h-4" />
              ) : (
                <ChevronLeft className="w-4 h-4" />
              )}
            </Button>
          )}
        </div>
      </div>

      {/* 导航菜单 */}
      <div className={cn(
        "flex-1 overflow-y-auto p-4",
        isCollapsed ? "p-2" : "p-4"
      )}>
        <nav className="space-y-2">
          {menus.map((menu) => (
            <div key={menu.id}>
              {/* 一级菜单 */}
              {menu.children ? (
                <Collapsible
                  open={expandedMenus.has(menu.id)}
                  onOpenChange={(open) => {
                    if (open) {
                      setExpandedMenus(prev => new Set(prev).add(menu.id));
                    } else {
                      setExpandedMenus(prev => {
                        const newSet = new Set(prev);
                        newSet.delete(menu.id);
                        return newSet;
                      });
                    }
                  }}
                >
                  <CollapsibleTrigger asChild>
                    <Button
                      variant="ghost"
                      className={cn(
                        "w-full justify-between text-sm font-normal group",
                        isCollapsed ? "justify-center px-2 py-3" : "px-3 py-2",
                        isMenuActive(menu) && "text-primary"
                      )}
                      title={isCollapsed ? menu.label : undefined}
                    >
                      <div className="flex items-center gap-2">
                        {menu.icon && (
                          <span className={cn(
                            "flex-shrink-0",
                            isMenuActive(menu) ? "text-primary" : "text-muted-foreground group-hover:text-primary"
                          )}>
                            {menu.icon}
                          </span>
                        )}
                        {!isCollapsed && (
                          <span>{menu.label}</span>
                        )}
                      </div>
                      {menu.children && (
                        isCollapsed ? null : (
                          <ChevronRight
                            className={cn(
                              "h-4 w-4 shrink-0 transition-transform duration-200",
                              expandedMenus.has(menu.id) && "rotate-90"
                            )}
                          />
                        )
                      )}
                    </Button>
                  </CollapsibleTrigger>
                  <CollapsibleContent>
                    {/* 二级菜单 */}
                    {!isCollapsed && (
                      <div className="ml-4 mt-1 space-y-1">
                        {menu.children.map((child) => (
                          <Button
                            key={child.id}
                            variant={activePath === child.path ? "secondary" : "ghost"}
                            className={cn(
                              "w-full justify-start text-xs font-normal h-8",
                              activePath === child.path
                                ? "bg-primary/10 text-primary font-medium hover:bg-primary/10"
                                : "hover:bg-accent hover:text-foreground"
                            )}
                            onClick={() => child.path && onNavigate(child.path)}
                          >
                            {child.label}
                          </Button>
                        ))}
                      </div>
                    )}
                  </CollapsibleContent>
                </Collapsible>
              ) : (
                <Button
                  variant="ghost"
                  className={cn(
                    "w-full justify-start text-sm font-normal group",
                    isCollapsed ? "justify-center px-2 py-3" : "px-3 py-2",
                    isMenuActive(menu) && "text-primary"
                  )}
                  title={isCollapsed ? menu.label : undefined}
                >
                  <div className="flex items-center gap-2">
                    {menu.icon && (
                      <span className={cn(
                        "flex-shrink-0",
                        isMenuActive(menu) ? "text-primary" : "text-muted-foreground group-hover:text-primary"
                      )}>
                        {menu.icon}
                      </span>
                    )}
                    {!isCollapsed && (
                      <span>{menu.label}</span>
                    )}
                  </div>
                </Button>
              )}
            </div>
          ))}
        </nav>
      </div>

      {/* 底部 */}
      <div className="p-4 border-t">
        <div className={cn(
          "text-xs text-muted-foreground",
          isCollapsed ? "text-center" : "text-left"
        )}>
          {isCollapsed ? "管理" : "管理系统"}
        </div>
      </div>
    </div>
  );
}