import React, { Children, cloneElement } from 'react';
import PropTypes from 'prop-types';
import { Avatar } from '../../atoms/avatar/Avatar';

const propTypes = {
  /**
   * The AvatarStack content (should be a list of Avatar components).
   */
  children: PropTypes.node,

  /**
   * The Avatar children border color.
   */
  variantBorderColor: PropTypes.oneOf(['light', 'dark']),
};

const defaultProps = {
  children: [],
  variantBorderColor: 'light',
};

export const AvatarStack = ({ children, variantBorderColor, ...props }) => {
  const childrenCount = Children.count(children);

  return (
    <>
      {Children.map(
        children,
        (child, index) => {
          if (index < 3) {
            // If there is more than three avatars, we want to print the number
            // of users in the third avatar.
            if (index === 2 && childrenCount - 2 > 1) {
              return (
                <Avatar
                  isStacked={variantBorderColor === 'light'}
                  isStackedDark={variantBorderColor === 'dark'}
                  {...props}
                  plus={childrenCount - 2}
                />
              );
            }

            return (
              cloneElement(child, {
                isStacked: variantBorderColor === 'light',
                isStackedDark: variantBorderColor === 'dark',
                ...props,
              })
            );
          }

          return null;
        }
      )}
    </>
  );
};

AvatarStack.propTypes = propTypes;
AvatarStack.defaultProps = defaultProps;
