import React, { forwardRef, useState, HTMLAttributes } from 'react';
import { clsx } from 'clsx';

export interface AvatarProps extends HTMLAttributes<HTMLDivElement> {
  src?: string;
  alt?: string;
  size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl';
  shape?: 'circle' | 'square';
  name?: string;
  status?: 'online' | 'offline' | 'away' | 'busy';
  statusPosition?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
  showStatusText?: boolean;
  badge?: React.ReactNode;
  badgePosition?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
  icon?: React.ReactNode;
  onClick?: () => void;
  loading?: boolean;
  fallback?: React.ReactNode;
  borderColor?: string;
  borderWidth?: number;
}

export interface AvatarGroupProps extends HTMLAttributes<HTMLDivElement> {
  max?: number;
  size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl';
  shape?: 'circle' | 'square';
  spacing?: 'tight' | 'normal' | 'loose';
  showMore?: boolean;
  moreText?: string;
  onMoreClick?: () => void;
}

const Avatar = forwardRef<HTMLDivElement, AvatarProps>(({
  src,
  alt,
  size = 'md',
  shape = 'circle',
  name,
  status,
  statusPosition = 'bottom-right',
  showStatusText = false,
  badge,
  badgePosition = 'top-right',
  icon,
  onClick,
  loading = false,
  fallback,
  borderColor,
  borderWidth = 2,
  className,
  children,
  ...props
}, ref) => {
  const [imageError, setImageError] = useState(false);
  const [imageLoaded, setImageLoaded] = useState(false);

  const handleImageError = () => {
    setImageError(true);
    setImageLoaded(false);
  };

  const handleImageLoad = () => {
    setImageLoaded(true);
    setImageError(false);
  };

  // Generate initials from name
  const getInitials = (name: string): string => {
    return name
      .split(' ')
      .map(word => word.charAt(0))
      .join('')
      .toUpperCase()
      .slice(0, 2);
  };

  // Generate background color from name
  const getBackgroundColor = (name: string): string => {
    const colors = [
      '#f59e0b', '#ef4444', '#10b981', '#3b82f6', '#8b5cf6',
      '#f97316', '#06b6d4', '#84cc16', '#ec4899', '#6366f1'
    ];
    
    let hash = 0;
    for (let i = 0; i < name.length; i++) {
      hash = name.charCodeAt(i) + ((hash << 5) - hash);
    }
    
    return colors[Math.abs(hash) % colors.length];
  };

  const sizeClasses = {
    xs: 'w-6 h-6 text-xs',
    sm: 'w-8 h-8 text-sm',
    md: 'w-10 h-10 text-base',
    lg: 'w-12 h-12 text-lg',
    xl: 'w-16 h-16 text-xl',
    '2xl': 'w-20 h-20 text-2xl',
  };

  const shapeClasses = {
    circle: 'rounded-full',
    square: 'rounded-lg',
  };

  const statusClasses = {
    online: 'bg-[var(--color-success)]',
    offline: 'bg-[var(--text-tertiary)]',
    away: 'bg-[var(--color-warning)]',
    busy: 'bg-[var(--color-error)]',
  };

  const statusSizeClasses = {
    xs: 'w-2 h-2',
    sm: 'w-2 h-2',
    md: 'w-3 h-3',
    lg: 'w-3 h-3',
    xl: 'w-4 h-4',
    '2xl': 'w-4 h-4',
  };

  const statusPositionClasses = {
    'bottom-right': 'bottom-0 right-0',
    'bottom-left': 'bottom-0 left-0',
    'top-right': 'top-0 right-0',
    'top-left': 'top-0 left-0',
  };

  const badgePositionClasses = {
    'bottom-right': 'bottom-0 right-0 translate-x-1/2 translate-y-1/2',
    'bottom-left': 'bottom-0 left-0 -translate-x-1/2 translate-y-1/2',
    'top-right': 'top-0 right-0 translate-x-1/2 -translate-y-1/2',
    'top-left': 'top-0 left-0 -translate-x-1/2 -translate-y-1/2',
  };

  const baseClasses = [
    'relative inline-flex items-center justify-center',
    'bg-[var(--bg-tertiary)] text-[var(--text-primary)] font-medium',
    'overflow-hidden flex-shrink-0',
  ];

  const classes = clsx(
    baseClasses,
    sizeClasses[size],
    shapeClasses[shape],
    {
      'cursor-pointer hover:opacity-80 transition-opacity duration-200': onClick,
      'ring-2 ring-white': borderColor || borderWidth > 0,
    },
    className
  );

  const borderStyle = borderColor ? {
    borderColor,
    borderWidth: `${borderWidth}px`,
    borderStyle: 'solid',
  } : {};

  // Render content based on priority: children > src > name > icon > fallback
  const renderContent = () => {
    if (children) {
      return children;
    }

    if (loading) {
      return (
        <div className="animate-pulse bg-[var(--bg-quaternary)] w-full h-full" />
      );
    }

    if (src && typeof src === 'string' && src.trim() !== '' && !imageError) {
      return (
        <img
          src={src}
          alt={alt || (name ? `Avatar de ${name}` : 'Avatar')}
          className={clsx(
            'w-full h-full object-cover',
            shapeClasses[shape],
            {
              'opacity-0': !imageLoaded,
              'opacity-100': imageLoaded,
            }
          )}
          onError={handleImageError}
          onLoad={handleImageLoad}
        />
      );
    }

    if (name) {
      const initials = getInitials(name);
      const backgroundColor = getBackgroundColor(name);
      
      return (
        <span 
          className="text-white font-semibold"
          style={{ backgroundColor }}
        >
          {initials}
        </span>
      );
    }

    if (icon) {
      return (
        <span className="text-[var(--text-tertiary)]">
          {icon}
        </span>
      );
    }

    if (fallback) {
      return fallback;
    }

    // Default professional user icon
    return (
      <div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-[var(--color-primary)] to-[var(--color-primary-dark)] text-white">
        <svg
          className="w-3/5 h-3/5"
          fill="currentColor"
          viewBox="0 0 24 24"
          xmlns="http://www.w3.org/2000/svg"
        >
          {/* Professional user silhouette */}
          <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
        </svg>
      </div>
    );
  };

  const avatarElement = (
    <div
      ref={ref}
      className={classes}
      style={borderStyle}
      onClick={onClick}
      role={onClick ? 'button' : undefined}
      tabIndex={onClick ? 0 : undefined}
      onKeyDown={onClick ? (e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          onClick();
        }
      } : undefined}
      {...props}
    >
      {renderContent()}
      
      {/* Status indicator */}
      {status && (
        <span
          className={clsx(
            'absolute rounded-full ring-2 ring-[var(--bg-primary)]',
            statusClasses[status],
            statusSizeClasses[size],
            statusPositionClasses[statusPosition]
          )}
          aria-label={`Estado: ${status}`}
        />
      )}
      
      {/* Badge */}
      {badge && (
        <span
          className={clsx(
            'absolute transform',
            badgePositionClasses[badgePosition]
          )}
        >
          {badge}
        </span>
      )}
    </div>
  );

  // Show status text alongside avatar
  if (showStatusText && status) {
    const statusTextMap = {
      online: 'En línea',
      offline: 'Desconectado',
      away: 'Ausente',
      busy: 'Ocupado',
    };

    return (
      <div className="flex items-center gap-2">
        {avatarElement}
        <span className="text-sm text-[var(--text-secondary)]">
          {statusTextMap[status]}
        </span>
      </div>
    );
  }

  return avatarElement;
});

const AvatarGroup = forwardRef<HTMLDivElement, AvatarGroupProps>(({
  max = 5,
  size = 'md',
  shape = 'circle',
  spacing = 'normal',
  showMore = true,
  moreText,
  onMoreClick,
  className,
  children,
  ...props
}, ref) => {
  const childrenArray = React.Children.toArray(children);
  const visibleChildren = childrenArray.slice(0, max);
  const hiddenCount = childrenArray.length - max;

  const spacingClasses = {
    tight: '-space-x-1',
    normal: '-space-x-2',
    loose: '-space-x-3',
  };

  const classes = clsx(
    'flex items-center',
    spacingClasses[spacing],
    className
  );

  return (
    <div
      ref={ref}
      className={classes}
      {...props}
    >
      {visibleChildren.map((child, index) => (
        <div key={index} className="relative ring-2 ring-white">
          {React.cloneElement(child as React.ReactElement, {
            size,
            shape,
          })}
        </div>
      ))}
      
      {hiddenCount > 0 && showMore && (
        <div className="relative ring-2 ring-white">
          <Avatar
            size={size}
            shape={shape}
            onClick={onMoreClick}
            className="bg-[var(--bg-quaternary)] text-[var(--text-secondary)] cursor-pointer hover:bg-[var(--bg-tertiary)] transition-colors duration-200"
          >
            <span className="font-medium">
              {moreText || `+${hiddenCount}`}
            </span>
          </Avatar>
        </div>
      )}
    </div>
  );
});

Avatar.displayName = 'Avatar';
AvatarGroup.displayName = 'AvatarGroup';

export default Avatar;
export { AvatarGroup };