import {
  Children,
  cloneElement,
  CSSProperties,
  ReactNode,
  ReactElement,
} from 'react'
import classNames from 'classnames'
import { CommonComponentProps } from '../../utils/types'
import './Avatar.scss'

import { Avatar, AvatarProps } from './Avatar'

export interface AvatarGroupProps extends CommonComponentProps {
  className?: string
  style?: CSSProperties
  children?: ReactNode
  gap?: number
  direction?: 'left' | 'right'
  maxCount?: number
}

export function AvatarGroup(props: AvatarGroupProps) {
  const {
    className,
    children,
    gap,
    direction = 'right',
    maxCount = 5,
    ...restProps
  } = props

  const groupClass = classNames('s-avatar-group', className)

  const count = Children.count(children)

  return (
    <div {...restProps} className={groupClass}>
      {Children.map(
        children as ReactElement<AvatarProps>,
        (item: ReactElement<AvatarProps>, index) => {
          return index > maxCount - 1
            ? null
            : cloneElement(item, {
                style: {
                  marginLeft: index === 0 ? 0 : gap,
                  zIndex: direction === 'left' ? count - index : void 0,
                },
              })
        }
      )}
      {count > maxCount && (
        <Avatar className="s-avatar-rest">+{count - maxCount}</Avatar>
      )}
    </div>
  )
}

export default AvatarGroup
