import { AvatarGroup as AvatarGroupMui, useTheme } from '@mui/material';

import Avatar from '../Avatar';
import { getColorsVariant, getSizeInPixels } from '../Avatar/utils';

import { type AvatarGroupProps } from './types';

const MAX_AVATARS = 4;

export const formatSurplus = (surplus: number) =>
  surplus > 999 ? `+${Math.trunc(surplus / 1000)}K` : `+${surplus}`;

const AvatarGroup = ({
  size = 'medium',
  avatars,
  totalAvatars,
}: AvatarGroupProps) => {
  const theme = useTheme();
  const sizeInPixels = getSizeInPixels(size);
  const colorsVariant = getColorsVariant('default', theme);

  return (
    <AvatarGroupMui
      spacing="small"
      sx={{
        justifyContent: 'start',
        '& .MuiAvatar-root': {
          height: sizeInPixels,
          width: sizeInPixels,
          position: 'static',
          border: `1px solid ${theme.palette.new.border.neutral.default}`,
        },
      }}
      slotProps={{
        additionalAvatar: {
          sx: {
            height: sizeInPixels,
            width: sizeInPixels,
            fontSize: (totalAvatars || avatars.length) > 99 ? 14 : 'initial',
            border: `1px solid ${theme.palette.new.border.neutral.default}`,
            ...colorsVariant,
          },
        },
      }}
      max={MAX_AVATARS}
      renderSurplus={formatSurplus}
      total={totalAvatars || avatars.length}
    >
      {avatars.map(avatar => (
        <Avatar
          key={avatar.text || avatar.src}
          {...avatar}
        />
      ))}
    </AvatarGroupMui>
  );
};

export type { AvatarGroupProps };

export default AvatarGroup;
