import React from 'react';
import Avatar from '@mui/material/Avatar';
import type { AvatarProps } from '@mui/material/Avatar';

interface UserAvatarProps extends Omit<AvatarProps, 'src'> {
  photoUrl?: string | null;
  initials: string;
  fullName: string;
}

/**
 * Reusable user avatar component that displays profile photo if available,
 * otherwise shows initials with a colored background
 */
const UserAvatar = React.forwardRef<HTMLDivElement, UserAvatarProps>(({
  photoUrl,
  initials,
  fullName,
  sx,
  ...otherProps
}, ref) => {
  // Helper function to generate consistent color from string
  const stringToColor = (str: string): string => {
    // Handle undefined or empty string
    if (!str || str.length === 0) {
      return '#808080'; // Default gray color
    }

    let hash = 0;
    for (let i = 0; i < str.length; i++) {
      hash = str.charCodeAt(i) + ((hash << 5) - hash);
    }

    let color = '#';
    for (let i = 0; i < 3; i++) {
      const value = (hash >> (i * 8)) & 0xff;
      color += ('00' + value.toString(16)).substr(-2);
    }

    return color;
  };

  // If photoUrl is available and not null, use it
  if (photoUrl) {
    return (
      <Avatar
        ref={ref}
        src={photoUrl}
        alt={fullName}
        sx={sx}
        {...otherProps}
      >
        {/* Fallback to initials if image fails to load */}
        {initials}
      </Avatar>
    );
  }

  // Otherwise, show initials with colored background
  return (
    <Avatar
      ref={ref}
      sx={{
        bgcolor: stringToColor(fullName),
        ...sx,
      }}
      {...otherProps}
    >
      {initials}
    </Avatar>
  );
});

UserAvatar.displayName = 'UserAvatar';

export default UserAvatar;
