import React from "react";
import { Link, NavLink, useLocation, useNavigate } from "react-router-dom";
import menuData from "../../data/menuData.json";
import { getCachedProfileData } from "../../slices/apiDataManager";

const Sidebar = () => {
  const navigate = useNavigate();

  return (
    <aside
      id="layout-menu"
      className="layout-menu menu-vertical menu bg-menu-theme "
    >
      <div className="app-brand" style={{ paddingLeft: "30px" }}>
        <Link to="/dashboard" className="app-brand-link">
          <span className="app-brand-logo  rounded-circle app-brand-logo-border">
            <img
              className="app-brand-logo-sidebar"
              src="/img/brand/marco.png"
              alt="logo"
              aria-label="logo image"
              style={{ margin: "5px", paddingRight: "5px" }}
            />
          </span>
          <span className="app-brand-text  menu-text fw-bold ms-2">PMS</span>
        </Link>

        <a className="layout-menu-toggle menu-link text-large ms-auto">
          <i className="bx bx-chevron-left bx-sm d-flex align-items-center justify-content-center"></i>
        </a>
      </div>

      <div className="menu-inner-shadow"></div>

      <ul className="menu-inner py-1">
        {menuData.map((section) => (
          <React.Fragment key={(Math.random() + 1).toString(36)}>
            {section.header && (
              <li className="menu-header small text-uppercase">
                <span className="menu-header-text">{section.header}</span>
              </li>
            )}
            {section.items.map(MenuItem)}
          </React.Fragment>
        ))}
      </ul>
    </aside>
  );
};

const MenuItem = (item) => {
  item.id = Math.random();
  const location = useLocation();
  const isActive = location.pathname === item.link;
  const hasSubmenu = item.submenu && item.submenu.length > 0;
  const isSubmenuActive =
    hasSubmenu &&
    item.submenu.some((subitem) => location.pathname === subitem.link);

  return (
    <li
      key={(Math.random() + 1).toString(36)}
      className={`menu-item ${isActive || isSubmenuActive ? "active" : ""} ${
        hasSubmenu && isSubmenuActive ? "open" : ""
      }`}
    >
      <NavLink
        aria-label={`Navigate to ${item.text} ${!item.available ? "Pro" : ""}`}
        to={item.link}
        className={`menu-link ${item.submenu ? "menu-toggle" : ""}`}
        key={(Math.random() + 1).toString(36)}
        target={item.link.includes("http") ? "_blank" : undefined}
      >
        <i className={`menu-icon tf-icons ${item.icon}`}></i>
        <div>{item.text}</div>{" "}
        {item.available === false && (
          <div className="badge bg-label-primary fs-tiny rounded-pill ms-auto">
            Pro
          </div>
        )}
      </NavLink>
      {item.submenu && (
        <ul className="menu-sub" key={(Math.random() + 1).toString(36)}>
          {item.submenu.map(MenuItem)}
        </ul>
      )}
    </li>
  );
};

export default Sidebar;
