import type { MenuProps } from "antd";

import { Menu } from "antd";
import { useLocation, useNavigate } from "react-router";

import { MENU_ITEMS } from "../../menu";

type MenuItem = Required<MenuProps>["items"][number];

export function Sidebar() {
  const navigate = useNavigate();
  const location = useLocation();

  const currentPath = location.pathname;
  const currentItem = MENU_ITEMS.find((item) => item.path === currentPath);
  const selectedKeys = currentItem ? [currentItem.value] : [];

  const menuItems: MenuItem[] = MENU_ITEMS.map((item) => ({
    icon: item.icon,
    key: item.value,
    label: item.label,
  }));

  const handleMenuClick: MenuProps["onClick"] = ({ key }) => {
    const item = MENU_ITEMS.find((i) => i.value === key);
    if (item) {
      void navigate(item.path);
    }
  };

  return <Menu items={menuItems} mode="inline" onClick={handleMenuClick} selectedKeys={selectedKeys} />;
}
