import React, { useMemo } from 'react';
import { Layout, Menu } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import { useTheme } from '@/contexts/ThemeContext';
import { getMenuItems } from '@/utils/menuUtils';
import { Logo } from '@/components/common/Logo';

const { Sider } = Layout;

const Sidebar = ({ collapsed }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const { isDarkMode } = useTheme();

  const menuItems = useMemo(() => getMenuItems(), []);

  const defaultOpenKeys = useMemo(() => {
    const pathSegments = location.pathname.split('/').filter(Boolean);
    return pathSegments.reduce((acc, _, index) => {
      const path = `/${pathSegments.slice(0, index + 1).join('/')}`;
      acc.push(path);
      return acc;
    }, []);
  }, [location.pathname]);

  // Handle menu item click
  const handleMenuClick = ({ key }) => {
    navigate(key);
  };

  return (
    <Sider 
      trigger={null} 
      collapsible 
      collapsed={collapsed}
      theme={isDarkMode ? 'dark' : 'light'}
      width={256}
      collapsedWidth={80} // 添加这个属性
       className={`app-sidebar ${collapsed ? 'collapsed' : ''}`} // 添加collapsed类名
    >
      <Logo collapsed={collapsed} isDarkMode={isDarkMode} />
      <Menu
        theme={isDarkMode ? 'dark' : 'light'}
        mode="inline"
        selectedKeys={[location.pathname]}
        defaultOpenKeys={defaultOpenKeys}
        items={menuItems}
        onClick={handleMenuClick}
      />
    </Sider>
  );
};

export default React.memo(Sidebar);