import s from './styles.module.scss';
import { TMenuItem } from '@shared/const/menu';
import clsx from 'clsx';
import { MenuList } from '@widgets/sidebar/menu-list';
import Link from 'next/link';

type MenuItemProps = {
  item: TMenuItem;
  level: number;
  isOpen: boolean;
  onToggle: () => void;
  onClose: () => void;
};

function MenuItem({ item, level, onToggle, onClose, isOpen }: MenuItemProps) {
  const hasChildren = !!item.children?.length;

  const onLinkClick = () => {
    onClose();
  };

  return (
    <li className={s.MenuItem}>
      <div
        className={clsx(s.MenuTitle, hasChildren && s.MenuTitle_hasChildren)}
        onClick={hasChildren ? onToggle : undefined}
      >
        {hasChildren ? (
          <>{item.title}</>
        ) : (
          <Link href={item.link ?? '#'} onClick={onLinkClick}>
            {item.title}
          </Link>
        )}

        {hasChildren && (
          <span className={clsx(s.Arrow, isOpen && s.Arrow_open)} />
        )}
      </div>

      {hasChildren && (
        <div className={clsx(s.Submenu, isOpen && s.Submenu_open)}>
          <MenuList
            items={item.children!}
            level={level + 1}
            onClose={onClose}
            isOpen={isOpen}
          />
        </div>
      )}
    </li>
  );
}

export { MenuItem };
