import { useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { PanelMenu } from 'primereact/panelmenu';
import { MENU_ITEMS, LAYOUT } from '@/core/constants/app.constants';
import { useCurrentUser } from '@/core/hooks/useCurrentUser';
import logo from '@/assets/images/logo.svg';
import './AppSidebar.scss';

interface Props {
  visible: boolean;
  collapsed: boolean;
  mobile: boolean;
}

export default function AppSidebar({ visible, collapsed, mobile }: Props) {
  const { currentUser } = useCurrentUser();
  const navigate = useNavigate();

  const filteredMenu = useMemo(() => {
    const userRoles = currentUser?.roles ?? [];
    return MENU_ITEMS
      .filter((item) => item.roles.some((r) => userRoles.includes(r)))
      .map((item) => ({
        ...item,
        command: item.to ? () => navigate(item.to!) : undefined,
        items: item.items
          ? item.items
              .filter((sub) => sub.roles.some((r) => userRoles.includes(r)))
              .map((sub) => ({
                ...sub,
                command: () => navigate(sub.to),
              }))
          : undefined,
      }));
  }, [currentUser, navigate]);

  const classNames = [
    'app-sidebar',
    visible && 'app-sidebar--visible',
    collapsed && 'app-sidebar--collapsed',
    mobile && 'app-sidebar--mobile',
  ]
    .filter(Boolean)
    .join(' ');

  const style = mobile
    ? undefined
    : { width: collapsed ? `${LAYOUT.sidebarCollapsedWidth}px` : `${LAYOUT.sidebarWidth}px` };

  return (
    <aside className={classNames} style={style}>
      <div className="app-sidebar__header">
        <img src={logo} alt="WTM" className="app-sidebar__logo" />
        {!collapsed && <span className="app-sidebar__title">WTM</span>}
      </div>

      <nav className="app-sidebar__nav">
        <PanelMenu model={filteredMenu} className="app-sidebar__menu" />
      </nav>
    </aside>
  );
}
