import React, { FC, useMemo } from 'react';
import cn from 'classnames';

import { Tooltip } from '../Tooltip';
import { Popover } from '../Popover';
import { getColorByName, getText, getTooltip } from './utils';
import { StyledAvatar } from './styled-component';
import { useTheme } from '../Theme';
import { AvatarProps } from './types.d';

export const Avatar: FC<AvatarProps> = ({
  className = '',
  count,
  fontSize,
  img,
  lastName = '',
  name = '',
  onClick,
  size = 'medium',
  style = {},
  tooltip,
  popoverChild,
}) => {
  const theme = useTheme();
  const backgroundColor = useMemo(
    () => (count || img ? undefined : getColorByName(name, lastName)),
    [count, name, lastName, img]
  );
  const text = count ?? getText(name, lastName);
  const tooltipText = getTooltip(name, lastName, count, tooltip);
  const sizeNumber = typeof size === 'number' ? size : undefined;

  const classNames = cn({
    users__item: true,
    users__item_counter: !!count,
    [size]: true,
    [className]: true,
    clickable: !!onClick,
  });
  return popoverChild ? (
    <Popover
      anchor={{
        component: (
          <Tooltip title={tooltipText} key={name + lastName + (count?.toString() ?? '')}>
            <StyledAvatar
              className={classNames}
              style={{ ...style, backgroundColor, width: sizeNumber, height: sizeNumber, fontSize }}
              $theme={theme}
              $border={!!count}
            >
              {img ? <img className="users__pic" src={img} alt="" /> : text}
            </StyledAvatar>
          </Tooltip>
        ),
      }}
    >
      {popoverChild}
    </Popover>
  ) : (
    <Tooltip title={tooltipText} key={name + lastName + (count?.toString() ?? '')}>
      <StyledAvatar
        className={classNames}
        style={{ ...style, backgroundColor, width: sizeNumber, height: sizeNumber, fontSize }}
        $theme={theme}
        $border={!!count}
        onClick={onClick}
      >
        {img ? <img className="users__pic" src={img} alt="" /> : text}
      </StyledAvatar>
    </Tooltip>
  );
};
