import { memo } from 'react';
import { getInitials, generateAvatarColor } from '../../../utils/utils';

interface AvatarProps {
  src?: string | null;
  name: string;
  size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl' | '3xl';
  className?: string;
  online?: boolean;
}

const sizeClasses = {
  xs: 'w-6 h-6 text-[10px]',
  sm: 'w-8 h-8 text-xs',
  md: 'w-10 h-10 text-sm',
  lg: 'w-12 h-12 text-base',
  xl: 'w-20 h-20 text-xl',
  '2xl': 'w-32 h-32 text-4xl',
  '3xl': 'w-40 h-40 text-5xl',
} as const;

const onlineDotSize = {
  xs: 'w-1.5 h-1.5 border',
  sm: 'w-2 h-2 border',
  md: 'w-2.5 h-2.5 border-2',
  lg: 'w-3 h-3 border-2',
  xl: 'w-4 h-4 border-2',
  '2xl': 'w-6 h-6 border-4',
  '3xl': 'w-8 h-8 border-4',
} as const;

const roundingClasses = {
  xs: 'rounded-lg',
  sm: 'rounded-xl',
  md: 'rounded-xl',
  lg: 'rounded-2xl',
  xl: 'rounded-3xl',
  '2xl': 'rounded-[1.5rem]',
  '3xl': 'rounded-[2rem]',
} as const;

function AvatarInner({ src, name, size = 'md', className = '', online }: AvatarProps) {
  const sizeClass = sizeClasses[size];
  const rounding = roundingClasses[size];
  const initials = getInitials(name || '?');
  const gradientClass = generateAvatarColor(name || '');

  return (
    <div className={`relative shrink-0 ${sizeClass} ${rounding} ${className} overflow-hidden`}>
      {src ? (
        <img
          src={src}
          alt={name}
          className="w-full h-full object-cover"
        />
      ) : (
        <div
          className={`w-full h-full ${gradientClass} flex items-center justify-center text-on-primary font-black tracking-tighter`}
        >
          {initials}
        </div>
      )}
      {online !== undefined && (
        <div
          className={`absolute bottom-0 right-0 ${onlineDotSize[size]} rounded-full border-surface-container ${
            online ? 'bg-success shadow-[0_0_8px_rgba(76,175,80,0.5)]' : 'bg-on-surface-variant/20'
          }`}
        />
      )}
    </div>
  );
}

const Avatar = memo(AvatarInner);
export default Avatar;
