import { Avatar } from 'antd';
import { UserOutlined } from '@ant-design/icons';
import OnlineIndicator from './OnlineIndicator';

/** Generate consistent color from string hash */
function stringToColor(str: string): string {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash);
  }
  const hue = Math.abs(hash) % 360;
  return `hsl(${hue}, 65%, 45%)`;
}

function getInitials(name: string | null | undefined, email?: string): string {
  if (name) {
    const parts = name.trim().split(/\s+/);
    if (parts.length >= 2) return (parts[0]![0]! + parts[parts.length - 1]![0]!).toUpperCase();
    return parts[0]!.slice(0, 2).toUpperCase();
  }
  if (email) return email[0]!.toUpperCase();
  return '?';
}

interface UserAvatarProps {
  userId: string;
  name?: string | null;
  email?: string;
  size?: number;
  style?: React.CSSProperties;
  showOnline?: boolean;
}

export default function UserAvatar({ userId, name, email, size = 32, style, showOnline = false }: UserAvatarProps) {
  const initials = getInitials(name, email);
  const bgColor = stringToColor(userId);

  const avatar = (
    <Avatar
      size={size}
      style={{ backgroundColor: bgColor, fontWeight: 600, fontSize: size * 0.4, ...style }}
      icon={!name && !email ? <UserOutlined /> : undefined}
    >
      {(name || email) && initials}
    </Avatar>
  );

  if (!showOnline) return avatar;

  return (
    <div style={{ position: 'relative', display: 'inline-block' }}>
      {avatar}
      <OnlineIndicator
        userId={userId}
        size={Math.max(8, size * 0.3)}
        style={{
          position: 'absolute',
          bottom: 0,
          right: 0,
        }}
      />
    </div>
  );
}
