import { Text } from "@contentful/f36-components";
import { useMenu } from "@/contexts/MenuContext";
import { useNavigate, useLocation } from "react-router-dom";
import type { JeecgMenu } from "@/types/menu";
import styles from "./index.module.css";

interface SidebarItemProps {
  menu: JeecgMenu;
  active?: boolean;
  onClick?: () => void;
}

function SidebarItem({ menu, active, onClick }: SidebarItemProps) {
  return (
    <div
      className={`${styles.menuItem} ${active ? styles.menuItemActive : ""}`}
      onClick={onClick}
    >
      <Text>{menu.meta?.title || menu.name}</Text>
    </div>
  );
}

export default function Sidebar() {
  const { activeFirstMenu, activeSecondMenu, setActiveSecondMenu } = useMenu();
  const navigate = useNavigate();
  const location = useLocation();

  if (!activeFirstMenu || !activeFirstMenu.children || activeFirstMenu.children.length === 0) {
    return null;
  }

  const secondMenus = activeFirstMenu.children.filter((menu) => !menu.hidden && !menu.meta?.hideMenu);

  const handleMenuClick = (menu: JeecgMenu) => {
    console.log("Sidebar: Clicked menu", menu.name, menu.path);
    setActiveSecondMenu(menu);
    const menuPath = menu.path || "";
    navigate(menuPath);
  };

  return (
    <aside className={styles.sidebar}>
      {secondMenus.map((menu) => {
        const menuPath = menu.path || "";
        const isActive = location.pathname === menuPath || activeSecondMenu?.id === menu.id;
        
        return (
          <SidebarItem
            key={menu.id}
            menu={menu}
            active={isActive}
            onClick={() => handleMenuClick(menu)}
          />
        );
      })}
    </aside>
  );
}
