import React, { useMemo,useEffect } 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/Layout/Logo";
import { useAuth } from "@/contexts/AuthContext";

const { Sider } = Layout;

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

  const getSelectedKeys = useMemo(() => {
    const pathname = location.pathname.substring(1);
    
    const pathParts = pathname.split('/');
    let key = '';
    
    if (pathParts.length >= 2) {
      const baseKey = `${pathParts[0]}/${pathParts[1]}`;
      key = pathname.includes('/') ? baseKey : pathname;
    } else {
      key = pathname;
    }
    
    return [key];
  }, [location.pathname]);

  const menuClient = useMemo(() => {
    if (!user?.id || user.menukeys?.length === 0) return [];
    return getMenuItems(user?.menukeys || []);
  }, [user]);

  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]);

  const selectedKey = useMemo(() => {
    return location.pathname;
  }, [location.pathname]);

  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" : ""} overflow-auto`} 
    >
      <Logo collapsed={collapsed} isDarkMode={isDarkMode} />
      <Menu
        theme={isDarkMode ? "dark" : "light"}
        mode="inline"
        selectedKeys={[selectedKey]}
        defaultOpenKeys={defaultOpenKeys}
        items={menuClient}
        onClick={handleMenuClick}
      />
    </Sider>
  );
};

export default React.memo(Sidebar);
