import React, { useEffect, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import classNames from 'clsx';

import { DEMAND_TAG_PRIORITY } from '../../constants';

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

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

function NameCell(props) {
  const ref = useRef(null);
  const [isTruncated, setIsTruncated] = useState(false);

  useEffect(() => {
    const handleResize = () => {
      setTimeout(() => setIsTruncated(ref.current?.scrollWidth > ref.current?.offsetWidth), 300);
    };

    handleResize();

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  const name = typeof props.cell.name === 'string' ? props.cell.name : props.cell;
  const isFirstLook = props.cell?.dtPriority === DEMAND_TAG_PRIORITY.firstLook;

  return isTruncated ? (
    <Tooltip title={name} placement="top">
      <div
        ref={ref}
        className={classNames(styles.NameCell, {
          [styles.NameCell___bold]: isFirstLook,
        })}
      >
        {name}

        {isFirstLook && (
          <UserAvatar className={styles.Avatar} size="xSmall" id="firstLook" firstName="F" lastName="L" />
        )}
      </div>
    </Tooltip>
  ) : (
    <div
      ref={ref}
      className={classNames(styles.NameCell, {
        [styles.NameCell___bold]: isFirstLook,
      })}
    >
      {name}

      {isFirstLook && <UserAvatar className={styles.Avatar} size="xSmall" id="firstLook" firstName="F" lastName="L" />}
    </div>
  );
}

NameCell.propTypes = {
  cell: PropTypes.string.isRequired,
};

export default NameCell;
