import React from 'react';
import { Avatar, AvatarColorVariant, AvatarSizeVariant } from 'components/avatar';
import { Row, Visible } from 'components';
import { Container, StyleSystemThemedProps } from 'components/layout';
import { AvatarShapeVariant } from 'components/avatar/Avatar';
import { Text } from 'components/text';

/**
 *
 * Displays a group of avatars inline up to 3 of the users in the list and shows the remaining count
 *
 * @param props - The list configuration for the avatars
 * @returns
 */
const avatarOverlapMargin: Record<AvatarSizeVariant, number> = {
  'extra-small': 8,
  small: 9,
  medium: 12,
  large: 15,
  'extra-large': 16.5,
};
export const AvatarList: React.FC<AvatarListType> = ({
  users,
  variant,
  shapeVariant,
  sizeVariant,
  size,
  colorVariant,
  showExtra = false,
  bordered,
  avatarCount = 3,
  ...props
}) => {
  let marginLeft = -7;
  if (sizeVariant) {
    marginLeft = sizeVariant ? -avatarOverlapMargin[sizeVariant] : -(size as number) * 0.3;
  }

  const avatars = users.length > avatarCount ? users.slice(0, avatarCount) : users;
  const extraCount = users.length > avatarCount ? users.length - avatarCount : 0;
  const borderWidth = variant === 'outline' ? 1 : 0;
  return (
    <Row
      borderColor="divider"
      p="3xs"
      borderRadius={7}
      borderWidth={borderWidth}
      alignItems="center"
      {...props}
    >
      {avatars.map(({ uri, id, icon, title }, index) => {
        return (
          <Avatar
            zIndex={-index}
            colorVariant={colorVariant}
            marginLeft={index > 0 ? marginLeft : 0}
            icon={icon}
            key={id}
            bordered={bordered}
            title={title}
            shapeVariant={shapeVariant}
            sizeVariant={sizeVariant}
            uri={uri}
            size={size}
          />
        );
      })}
      <Visible if={showExtra}>
        <Container mx="2xs">
          <Text variant="caption">{`+${extraCount.toString()}`}</Text>
        </Container>
      </Visible>
    </Row>
  );
};
type AvatarListType = StyleSystemThemedProps & AvatarListProps;
export type AvatarListVariant = 'outline' | 'plain';
export type AvatarUser = {
  title?: string;
  id: string;
  icon?: JSX.Element;
  uri?: string;
};
export interface AvatarListProps {
  users: AvatarUser[];
  variant?: AvatarListVariant;
  avatarCount?: number;
  showExtra?: boolean;
  bordered?: boolean;
  sizeVariant?: AvatarSizeVariant;
  colorVariant?: AvatarColorVariant;
  shapeVariant?: AvatarShapeVariant;
  size?: number;
}
