import { type FC } from 'react';
import { Link as RouterLink } from 'react-router-dom';

import Link from '@material-hu/mui/Link';
import Typography, { type TypographyProps } from '@material-hu/mui/Typography';

import { profileRoutes } from 'src/pages/dashboard/profile/routes';
import { type User } from 'src/types/user';
import { getFullName } from 'src/utils/userUtils';

export type RegularChatNameProps = Pick<TypographyProps, 'color'> &
  Pick<TypographyProps, 'sx'> & {
    otherUser: User;
    otherUserId?: number;
    withLink?: boolean;
    className?: string;
    withUserDeleted?: boolean;
  };

const RegularChatName: FC<RegularChatNameProps> = props => {
  const {
    otherUser,
    otherUserId,
    withLink = true,
    withUserDeleted = false,
    sx = {},
    ...typographyProps
  } = props;

  const renderUserName = () =>
    otherUser && (
      <Typography
        color={
          withUserDeleted ? 'grey' : typographyProps.color || 'textPrimary'
        }
        variant="subtitle2"
      >
        {otherUser.fullName || getFullName(otherUser)}
      </Typography>
    );

  const renderUserLink = () =>
    otherUser && (
      <Link
        color={
          withUserDeleted ? 'grey' : typographyProps.color || 'textPrimary'
        }
        component={RouterLink}
        to={profileRoutes.profile(otherUser?.id ? otherUser.id : otherUserId)}
        variant="subtitle2"
        sx={{
          textDecoration: 'none',
          marginLeft: '0px !important',
          '&:hover': {
            textDecoration: 'underline',
          },
          ...sx,
        }}
        {...typographyProps}
      >
        {renderUserName()}
      </Link>
    );

  return (
    <Typography
      {...typographyProps}
      sx={sx}
      component="span"
      style={{
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
      }}
    >
      {withLink && !otherUser?.deleted ? renderUserLink() : renderUserName()}
    </Typography>
  );
};

export default RegularChatName;
