'use client';

import { useState, useEffect } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { LeftSidebar } from './components/LeftSidebar';
import { MainContent } from './components/MainContent';
import { cn } from '@/lib/utils';

// 菜单项数据结构定义
interface NavItem {
  title: string;
  url: string;
  icon: string;
  items?: {
    title: string;
    url: string;
    isActive?: boolean;
  }[];
}

interface SideBarData {
  navMain: NavItem[];
}


interface SideBarOldProps {
  children: React.ReactNode;
  activePath?: string;
  onNavigate?: (path: string) => void;
  data?: SideBarData;
}

const defaultSideBarData: SideBarData = {
  navMain: [
    {
      title: "租户管理",
      url: "/central-config/tenant",
      icon: "🏢",
      items: [
        {
          title: "企业审核",
          url: "/central-config/tenant/enterprise-audit",
          isActive: false
        },
        {
          title: "审核历史",
          url: "/central-config/tenant/audit-history",
          isActive: false
        },
        {
          title: "企业信息",
          url: "/central-config/tenant/enterprise-info",
          isActive: false
        },
        {
          title: "用户管理",
          url: "/central-config/tenant/user-management",
          isActive: false
        }
      ]
    },
    {
      title: "用户管理",
      url: "/central-config/user",
      icon: "👥",
      items: [
        {
          title: "员工管理",
          url: "/central-config/user/employee",
          isActive: false
        },
        {
          title: "角色管理",
          url: "/central-config/user/role",
          isActive: false
        },
        {
          title: "菜单管理",
          url: "/central-config/user/menu",
          isActive: false
        },
        {
          title: "权限配置管理",
          url: "/central-config/user/permission",
          isActive: false
        }
      ]
    },
    {
      title: "系统参数",
      url: "/central-config/system",
      icon: "🔧",
      items: [
        {
          title: "系统设置",
          url: "/central-config/system/settings",
          isActive: false
        },
        {
          title: "分类字典",
          url: "/central-config/system/category",
          isActive: false
        },
        {
          title: "数据字典",
          url: "/central-config/system/dictionary",
          isActive: false
        }
      ]
    },
    {
      title: "系统监控",
      url: "/central-config/monitor",
      icon: "📈",
      items: [
        {
          title: "登录日志",
          url: "/central-config/monitor/login-log",
          isActive: false
        },
        {
          title: "操作日志",
          url: "/central-config/monitor/operation-log",
          isActive: false
        },
        {
          title: "性能监控",
          url: "/central-config/monitor/performance",
          isActive: false
        },
        {
          title: "网络日志",
          url: "/central-config/monitor/network-log",
          isActive: false
        }
      ]
    },
    {
      title: "消息中心",
      url: "/central-config/message",
      icon: "📨",
      items: [
        {
          title: "消息发送",
          url: "/central-config/message/send",
          isActive: false
        },
        {
          title: "消息模版",
          url: "/central-config/message/template",
          isActive: false
        },
        {
          title: "消息日志",
          url: "/central-config/message/log",
          isActive: false
        }
      ]
    }
  ]
};


export function SideBarOld({
  children,
  activePath,
  onNavigate,
  data
}: SideBarOldProps) {
  const router = useRouter();
  const pathname = usePathname();
  const [isMobile, setIsMobile] = useState(false);
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [currentPath, setCurrentPath] = useState(pathname || activePath || '/machinery/list');

  // 使用传入的数据或默认数据
  const sidebarData = data || defaultSideBarData;

  // 转换为 MenuItem 格式以兼容 LeftSidebar 组件
  const menus = sidebarData.navMain.map(item => ({
    id: item.url.replace(/\/[^\/]+/g, '').replace('/', '') || item.title.replace(/\s+/g, '-').toLowerCase(),
    label: item.title,
    icon: item.icon,
    children: item.items?.map(child => ({
      id: child.url.split('/').pop() || child.title.replace(/\s+/g, '-').toLowerCase(),
      label: child.title,
      path: child.url,
    })),
  }));

  // 检测是否为移动设备
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth < 768);
    };

    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);
    return () => window.removeEventListener('resize', checkIsMobile);
  }, []);

  // 监听路由变化，同步当前路径
  useEffect(() => {
    if (pathname) {
      setCurrentPath(pathname);
    }
  }, [pathname]);

  // 移动端时自动展开侧边栏
  useEffect(() => {
    if (isMobile) {
      setIsCollapsed(false);
    }
  }, [isMobile]);

  const handleNavigate = (path: string) => {
    setCurrentPath(path);
    onNavigate?.(path);
    // 使用 Next.js 标准路由跳转
    router.push(path);
  };
  return (
    <div className={cn(
      "flex h-full bg-background",
      "min-h-0"  // 确保父容器有正确的高度约束
    )}>
      {/* 左侧导航栏 - 独立滚动 */}
      {!isMobile && (
        <div className="sidebarScroll">
          <LeftSidebar
            menus={menus}
            activePath={currentPath}
            onNavigate={handleNavigate}
            isMobile={isMobile}
            isCollapsed={isCollapsed}
            onToggleCollapse={() => setIsCollapsed(!isCollapsed)}
          />
        </div>
      )}

      {/* 右侧主内容 - 独立滚动 */}
      <div className="flex-1 contentScroll">
        <MainContent
          isMobile={isMobile}
          sidebarOpen={!isCollapsed}
          onToggleSidebar={() => setIsCollapsed(!isCollapsed)}
        >
          {children}
        </MainContent>
      </div>

      {/* 移动端侧边栏 */}
      {isMobile && (
        <div className="fixed inset-y-0 left-0 z-50 w-64 sidebarScroll">
          <LeftSidebar
            menus={menus}
            activePath={currentPath}
            onNavigate={handleNavigate}
            isMobile={isMobile}
            isCollapsed={false}
            onToggleCollapse={() => {}}
          />
        </div>
      )}
    </div>
  );
}