import React, { useRef } from 'react';
import PropTypes from 'prop-types';
import classNames from 'clsx';
import NextLink from 'next/link';

import { Link, Tooltip } from '@/mui/components';

import styles from './SubMenu.module.scss';

// @todo need think about icon props. Now it replace to "_"
const getLinkTitle = (title, _, itemRef) => {
  const shouldCutText = itemRef.current?.offsetWidth < itemRef.current?.scrollWidth;

  return shouldCutText ? (
    <Tooltip disableInteractive title={title} placement="top">
      <span>{title}</span>
    </Tooltip>
  ) : (
    title
  );
};

function SubMenuNavLink({ parentName = null, icon = null, isWithoutBorder = null, ...props }) {
  const itemRef = useRef(null);
  return (
    <Link
      component={NextLink}
      href={props.to}
      onClick={props.hideListOnClick}
      variant="body2"
      fontWeight={400}
      className={classNames(styles.SubItem, styles.SubItem___link, {
        [styles.SubItem___withoutBorder]: isWithoutBorder,
      })}
      data-nesting={parentName}
      data-id={props.title}
    >
      <span ref={itemRef} className={styles.SubTitle}>
        {getLinkTitle(props.title, icon, itemRef)}
      </span>
    </Link>
  );
}

SubMenuNavLink.propTypes = {
  to: PropTypes.string.isRequired,
  parentName: PropTypes.string,
  title: PropTypes.string.isRequired,
  icon: PropTypes.string,
  isWithoutBorder: PropTypes.bool,
  hideListOnClick: PropTypes.func.isRequired,
};

export default SubMenuNavLink;
