import React, { ReactElement, Children } from "react";
import { twJoin } from "tailwind-merge";
import { UserAvatarGroupTooltip } from "./tooltip/UserAvatarGroupTooltip";

export type UserAvatarGroupProps = {
  children?: React.ReactNode;
  maxChildren?: number;
  tooltipTitle: string;
  vertical?: boolean;
  size?: number;
};

export const UserAvatarGroup = ({
  children,
  maxChildren = 5,
  tooltipTitle,
  vertical = false,
  size = 24,
}: UserAvatarGroupProps) => {
  const overlap = size / 6;
  const calculatedSize = (12 / 24) * size;
  let zIndexCounter = Children.count(children);
  const childrenArray = Children.toArray(children).slice(0, maxChildren);
  const remainingChildren = Children.toArray(children).slice(
    maxChildren
  ) as ReactElement[];

  return (
    <div className={twJoin("flex items-start", vertical && "flex-col")}>
      {childrenArray.map((element, index) => {
        zIndexCounter--;

        return (
          <div
            key={index}
            style={{
              zIndex: zIndexCounter,
              [vertical ? "marginTop" : "marginLeft"]:
                index !== 0 ? -overlap : undefined,
            }}
          >
            {element}
          </div>
        );
      })}

      {remainingChildren.length > 0 && (
        <UserAvatarGroupTooltip
          tooltipTitle={tooltipTitle}
          tooltipBody={remainingChildren}
        >
          <div
            className={twJoin(
              "flex cursor-default items-center justify-center rounded-full text-N100",
              "outline-none ring-B400FR hover:bg-N20A focus-visible:ring-3"
            )}
            tabIndex={0}
            style={{
              width: size,
              height: size,
              [vertical ? "marginTop" : "marginLeft"]: overlap,
            }}
          >
            <span className="font-sans" style={{ fontSize: calculatedSize }}>
              +{remainingChildren.length}
            </span>
          </div>
        </UserAvatarGroupTooltip>
      )}
    </div>
  );
};
