import React, { useState, useEffect } from "react";
import "./AvatarGroup.styles.scss";

const getInitials = (name = "") => {
  const [firstName, lastName] = name.split(" ");
  if (firstName && lastName) {
    return `${firstName.charAt(0)}${lastName.charAt(0)}`;
  }
  return name.charAt(0);
};

// Generate a consistent color based on the user's name
const getAvatarColor = (name = "") => {
  const colors = [
    "#FF6B6B", // Red
    "#4ECDC4", // Teal
    "#45B7D1", // Blue
    "#96CEB4", // Green
    "#FFEAA7", // Yellow
    "#DDA0DD", // Plum
    "#98D8C8", // Mint
    "#F7DC6F", // Light Yellow
    "#BB8FCE", // Light Purple
    "#85C1E9", // Light Blue
    "#F8C471", // Orange
    "#82E0AA", // Light Green
    "#F1948A", // Light Red
    "#85929E", // Gray
    "#D7BDE2", // Lavender
    "#1A237E", // Deep Purple
    "#283593", // Indigo
    "#283593", // Indigo
  ];

  // Create a simple hash from the name
  let hash = 0;
  for (let i = 0; i < name.length; i++) {
    hash = name.charCodeAt(i) + ((hash << 5) - hash);
  }

  // Use the hash to pick a color
  const colorIndex = Math.abs(hash) % colors.length;
  return colors[colorIndex];
};

export const ChatAvatar = ({ src, name, size }) => {
  const [hasError, setHasError] = useState(false);

  useEffect(() => {
    setHasError(false);
  }, [src]);

  const handleError = () => {
    setHasError(true);
  };

  const showImage = src && !hasError;
  const avatarColor = getAvatarColor(name);

  return (
    <div
      className={`avatar avatar--${size}`}
      title={name}
      style={!showImage ? { backgroundColor: avatarColor } : {}}
    >
      {showImage ? (
        <img src={src} alt={name} onError={handleError} />
      ) : (
        <span className="avatar__initials">{getInitials(name)}</span>
      )}
    </div>
  );
};

// A new component for displaying the "more" count as an avatar
const MoreAvatar = ({ count, size }) => {
  return (
    <div
      className={`avatar avatar--${size} avatar--more`}
      title={`${count} more`}
    >
      <span>+{count}</span>
    </div>
  );
};

const AvatarGroup = ({ avatars = [], maxAvatars = 3, size = "md" }) => {
  // Ensure maxAvatars is at least 1 and not more than the actual number of avatars
  const effectiveMaxAvatars = Math.min(Math.max(1, maxAvatars), avatars.length);
  const visibleAvatars = avatars.slice(0, effectiveMaxAvatars);
  const hiddenAvatarsCount = Math.max(0, avatars.length - effectiveMaxAvatars);

  return (
    <div className="avatar-stack">
      {visibleAvatars?.map((user, index) => {
        return (
          <div
            key={user.id || index}
            className={`avatar-wrapper avatar-wrapper--${size}`}
            style={{ zIndex: index }}
          >
            <ChatAvatar src={user.url} name={user.label} size={size} />
          </div>
        );
      })}
      {hiddenAvatarsCount > 0 && (
        <div
          className={`avatar-wrapper avatar-wrapper--${size}`}
          // The "more" avatar should always have the highest z-index
          style={{ zIndex: visibleAvatars.length + 1 }}
        >
          <MoreAvatar count={hiddenAvatarsCount} size={size} />
        </div>
      )}
    </div>
  );
};

export default AvatarGroup;
