import { Avatar, AvatarFallback } from "~/components/ui/avatar";
import { colorIsDarkSimple } from "~/components/etichette";
import { cn, getHexColorFromString, getInitials } from "~/lib/utils";
import type { UsersId } from "~/schemas/public/Users";

const colorOptions = new Map<string, string>();

export const getUserColor = (str: string) => {
  if (colorOptions.has(str)) {
    return colorOptions.get(str)!;
  } else {
    const usercolor = getHexColorFromString(str);
    colorOptions.set(str, usercolor);
    return usercolor;
  }
};

export const UserAvatar = ({
  userId,
  username,
  className,
}: {
  userId: UsersId;
  username?: string;
  className?: string;
}) => {
  const userColor = getUserColor(userId);

  return (
    <Avatar className={cn("size-20", className)}>
      <AvatarFallback
        style={{
          backgroundColor: userColor,
          color: colorIsDarkSimple(userColor) ? "#FFFFFF" : "#000000",
        }}
      >
        {username && getInitials(username)}
      </AvatarFallback>
    </Avatar>
  );
};
