import { twJoin } from "tailwind-merge";
import React from "react";
import BoringAvatar from "boring-avatars";

import theme from "../../theme/theme";

export type AvatarProps = {
  id: string;
  name: string;
  src?: string;
  avatarBorder?: boolean;
  size?: number;
  noBackground?: boolean;
  /**
   * Whether this element should be excluded from the accessibility tree.
   *
   * Use only when you provide accessibility information higher up the tree!
   */
  presentation?: boolean;
};

export const Avatar = ({
  name,
  id,
  src,
  avatarBorder,
  size = 24,
  noBackground = false,
  presentation = false,
}: AvatarProps) => {
  const calculatedSize = (14 / 24) * size;

  return (
    <div className="relative" style={{ width: size, height: size }}>
      {src ? (
        <img
          className="h-full w-full rounded-full"
          src={src}
          alt={name}
          role={presentation ? "presentation" : "img"}
        />
      ) : (
        <div
          className={twJoin(
            "h-full w-full rounded-full",
            avatarBorder &&
              "outline outline-1 -outline-offset-1 outline-[rgba(255,255,255,0.12)]",
            noBackground && "outline outline-1 -outline-offset-1 outline-N40"
          )}
          role={presentation ? "presentation" : "img"}
          aria-hidden={presentation ? "true" : undefined}
          aria-label={name}
        >
          <span
            className={twJoin(
              "text-shadow-S100 absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 cursor-default font-sans uppercase",
              noBackground ? "text-N700" : " text-N0"
            )}
            style={{ fontSize: calculatedSize }}
          >
            {name?.slice(0, 1)}
          </span>
          {!noBackground && (
            <BoringAvatar
              square={false}
              size={size}
              name={id}
              variant="marble"
              colors={[
                theme.palette.B300,
                theme.palette.Y300,
                theme.palette.P300,
                theme.palette.T300,
                theme.palette.B400,
                theme.palette.B400,
                theme.palette.Y400,
                theme.palette.R400,
                theme.palette.G400,
                theme.palette.P400,
                theme.palette.T400,
                theme.palette.B500,
                theme.palette.Y500,
                theme.palette.P500,
                theme.palette.T500,
              ]}
            />
          )}
        </div>
      )}
    </div>
  );
};
