import { useState } from 'react';

interface AvatarProps {
  src?: string | null;
  alt?: string;
  size?: 'sm' | 'md' | 'lg' | 'xl' | '2xl';
  className?: string;
  ring?: boolean;
  status?: 'online' | 'away' | 'offline';
}

export function Avatar({
  src,
  alt = 'Avatar',
  size = 'md',
  className = '',
  ring = false,
  status,
}: AvatarProps) {
  const [imageError, setImageError] = useState(false);

  const sizes = {
    sm: 'w-8 h-8',
    md: 'w-12 h-12',
    lg: 'w-16 h-16',
    xl: 'w-24 h-24',
    '2xl': 'w-32 h-32',
  };

  const statusSizes = {
    sm: 'w-2 h-2 bottom-0 right-0',
    md: 'w-3 h-3 bottom-0 right-0',
    lg: 'w-3.5 h-3.5 bottom-0.5 right-0.5',
    xl: 'w-4 h-4 bottom-1 right-1',
    '2xl': 'w-5 h-5 bottom-1.5 right-1.5',
  };

  const statusColors = {
    online: 'bg-[var(--color-liked)]',
    away: 'bg-amber-500',
    offline: 'bg-[var(--color-text-muted)]',
  };

  const ringStyles = ring
    ? 'ring-2 ring-[var(--color-desire)] ring-offset-2 ring-offset-[var(--color-void)]'
    : '';

  if (!src || imageError) {
    return (
      <div className={`relative ${className}`}>
        <div
          className={`
            ${sizes[size]}
            rounded-full
            bg-gradient-to-br from-[var(--color-surface-elevated)] to-[var(--color-surface)]
            border border-[var(--glass-border)]
            flex items-center justify-center
            ${ringStyles}
          `}
        >
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.5"
            className="w-1/2 h-1/2 text-[var(--color-text-muted)]"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z"
            />
          </svg>
        </div>

        {status && (
          <span
            className={`
              absolute ${statusSizes[size]}
              ${statusColors[status]}
              rounded-full
              border-2 border-[var(--color-void)]
            `}
          />
        )}
      </div>
    );
  }

  return (
    <div className={`relative ${className}`}>
      <img
        src={src}
        alt={alt}
        onError={() => setImageError(true)}
        className={`
          ${sizes[size]}
          rounded-full object-cover
          bg-[var(--color-surface)]
          ${ringStyles}
        `}
      />

      {status && (
        <span
          className={`
            absolute ${statusSizes[size]}
            ${statusColors[status]}
            rounded-full
            border-2 border-[var(--color-void)]
          `}
        />
      )}
    </div>
  );
}
