import React, { ElementRef, forwardRef } from "react"
import { classNames } from "../../utils"
import { Avatar, AvatarImageProps } from "../Avatar"
import { CenterAligned } from "../CenterAligned"
import { Flex, FlexProps } from "../Flex"

export type FacepileProps = FlexProps & {
  avatars: Pick<AvatarImageProps, "src" | "seed">[]
  size?: number
  /**
   * The margin between the avatars when they overlap.
   */
  overlapMargin?: number

  /**
   * The maximum number of avatars to display.
   */
  displayLimit?: number

  overrides?: {
    Avatar?: Partial<AvatarImageProps>
  }
}

export const Facepile = forwardRef<ElementRef<typeof Flex>, FacepileProps>(
  function Facepile(
    {
      avatars,
      className,
      size = 24,
      overlapMargin = 8,
      displayLimit = 3,
      overrides,
      ...rest
    },
    ref,
  ) {
    const avatarClassName = overrides?.Avatar?.className

    return (
      <Flex className={className} ref={ref} {...rest}>
        {avatars.slice(0, displayLimit).map((avatar, index) => (
          <Avatar
            key={avatar.src || avatar.seed}
            rounded
            seed={avatar.seed}
            size={size}
            src={avatar.src}
            style={{
              marginLeft: index > 0 ? `-${overlapMargin}px` : undefined,
            }}
            {...overrides?.Avatar}
            className={avatarClassName}
          />
        ))}
        {avatars.length > displayLimit && (
          <CenterAligned
            style={{
              minWidth: size,
              minHeight: size,
              marginLeft: `-${overlapMargin}px`,
            }}
            {...overrides?.Avatar}
            className={classNames(
              "rounded-full bg-text-primary px-1 font-mono text-xs text-bg-primary",
              avatarClassName,
            )}
          >
            +{avatars.length - displayLimit}
          </CenterAligned>
        )}
      </Flex>
    )
  },
)
