import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import SubMenu from './SubMenu';
import dataMenu from './dataMenu'; 

const Menu = ({ searchQuery }) => {
  const [activeMenu, setActiveMenu] = useState(null);

  const handleMenuClick = (name) => {
    setActiveMenu(name); // Menyimpan menu yang aktif
  };

  const filteredMenu = dataMenu.map((menuSection) => {
    const filteredItems = menuSection.items.filter((item) => {
      const itemName = item.name.toLowerCase();
      const matches = itemName.includes(searchQuery);
      const subMatches = item.subMenus?.some((subMenu) =>
        subMenu.name.toLowerCase().includes(searchQuery)
      );
      return matches || subMatches;
    });

    return {
      ...menuSection,
      items: filteredItems,
    };
  }).filter(section => section.items.length > 0); // Filter out sections without items

  return (
    <div className="sb-sidenav-menu mb-2">
      <div className="nav">
        {filteredMenu.map((menuSection, index) => (
          <React.Fragment key={index}>
            {menuSection.items.map((item, idx) => (
              // Jika item memiliki submenu, render SubMenu
              item.subMenus ? (
                <SubMenu
                  key={idx}
                  heading={item.name}
                  target={item.target}
                  iconClass={menuSection.iconClass}
                  subMenus={item.subMenus.filter(subMenu =>
                    subMenu.name.toLowerCase().includes(searchQuery)
                  )}
                  activeMenu={activeMenu}
                  onMenuClick={handleMenuClick}
                />
              ) : (
                // Jika item tidak memiliki submenu, gunakan <Link> untuk navigasi
                <Link
                  key={idx}
                  className={`nav-link ${activeMenu === item.name ? 'active' : ''}`} // Menambahkan kelas 'active' pada item yang dipilih
                  to={item.link}
                  onClick={() => handleMenuClick(item.name)} // Memperbarui state activeMenu saat item dipilih
                >
                  <div className="sb-nav-link-icon">
                    {item.iconClass && <i className={item.iconClass}></i>}
                  </div>
                  {item.name}
                </Link>
              )
            ))}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
};
  
export default Menu;
