import { useState, type ImgHTMLAttributes } from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@utils/cn';
import { User } from 'lucide-react';

const avatarVariants = cva(
  'relative inline-flex items-center justify-center overflow-hidden rounded-full bg-gray-100',
  {
    variants: {
      size: {
        xs: 'h-6 w-6 text-xs',
        sm: 'h-8 w-8 text-sm',
        md: 'h-10 w-10 text-base',
        lg: 'h-12 w-12 text-lg',
        xl: 'h-16 w-16 text-xl',
        '2xl': 'h-20 w-20 text-2xl',
      },
    },
    defaultVariants: {
      size: 'md',
    },
  }
);

export interface AvatarProps
  extends Omit<ImgHTMLAttributes<HTMLImageElement>, 'size' | 'src'>,
    VariantProps<typeof avatarVariants> {
  src?: string | null;
  alt?: string;
  fallback?: string;
  status?: 'online' | 'offline' | 'away' | 'busy';
}

const statusColors = {
  online: 'bg-success-500',
  offline: 'bg-gray-400',
  away: 'bg-warning-500',
  busy: 'bg-danger-500',
};

export function Avatar({
  src,
  alt = '',
  fallback,
  size,
  status,
  className,
  ...props
}: AvatarProps) {
  const [hasError, setHasError] = useState(false);

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

  const showFallback = !src || hasError;

  return (
    <div className={cn(avatarVariants({ size }), className)}>
      {showFallback ? (
        fallback ? (
          <span className="font-medium text-gray-600">{getInitials(fallback)}</span>
        ) : (
          <User className="h-1/2 w-1/2 text-gray-400" />
        )
      ) : (
        <img
          src={src}
          alt={alt}
          onError={() => setHasError(true)}
          className="h-full w-full object-cover"
          {...props}
        />
      )}
      {status && (
        <span
          className={cn(
            'absolute bottom-0 right-0 block rounded-full ring-2 ring-white',
            statusColors[status],
            size === 'xs' && 'h-1.5 w-1.5',
            size === 'sm' && 'h-2 w-2',
            size === 'md' && 'h-2.5 w-2.5',
            size === 'lg' && 'h-3 w-3',
            (size === 'xl' || size === '2xl') && 'h-4 w-4'
          )}
        />
      )}
    </div>
  );
}

// Avatar Group
export interface AvatarGroupProps {
  children: React.ReactNode;
  max?: number;
  size?: 'xs' | 'sm' | 'md' | 'lg';
  className?: string;
}

export function AvatarGroup({ children, max, size = 'md', className }: AvatarGroupProps) {
  const avatars = Array.isArray(children) ? children : [children];
  const visibleAvatars = max ? avatars.slice(0, max) : avatars;
  const extraCount = max ? Math.max(0, avatars.length - max) : 0;

  const overlapClasses = {
    xs: '-ml-1.5',
    sm: '-ml-2',
    md: '-ml-2.5',
    lg: '-ml-3',
  };

  return (
    <div className={cn('flex items-center', className)}>
      {visibleAvatars.map((avatar, index) => (
        <div
          key={index}
          className={cn(
            'relative ring-2 ring-white rounded-full',
            index > 0 && overlapClasses[size]
          )}
          style={{ zIndex: visibleAvatars.length - index }}
        >
          {avatar}
        </div>
      ))}
      {extraCount > 0 && (
        <div
          className={cn(
            avatarVariants({ size }),
            overlapClasses[size],
            'bg-gray-200 font-medium text-gray-600 ring-2 ring-white'
          )}
          style={{ zIndex: 0 }}
        >
          +{extraCount}
        </div>
      )}
    </div>
  );
}
