import React, { useState, useEffect } from 'react';
import { CollaborationUser } from '../client/useCollaboration';

interface UserAwareness {
  userId: string;
  userName: string;
  color: string;
  section: string;
  activity: 'viewing' | 'editing' | 'commenting';
  lastActivity: Date;
}

interface AwarenessIndicatorProps {
  section: string;
  awareness: UserAwareness[];
  currentUserId: string;
  position?: 'top' | 'bottom' | 'left' | 'right';
  className?: string;
}

/**
 * Awareness Indicator Component
 * Shows which users are viewing or interacting with a section
 */
export const AwarenessIndicator: React.FC<AwarenessIndicatorProps> = ({
  section,
  awareness,
  currentUserId,
  position = 'right',
  className = ''
}) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const [recentActivity, setRecentActivity] = useState<UserAwareness[]>([]);

  // Filter awareness for this section, excluding current user
  const sectionAwareness = awareness.filter(
    a => a.section === section && a.userId !== currentUserId
  );

  // Update recent activity (last 5 minutes)
  useEffect(() => {
    const now = new Date();
    const fiveMinutesAgo = new Date(now.getTime() - 5 * 60 * 1000);
    
    setRecentActivity(
      sectionAwareness.filter(a => a.lastActivity > fiveMinutesAgo)
    );
  }, [awareness, section]);

  if (recentActivity.length === 0) {
    return null;
  }

  const getActivityIcon = (activity: UserAwareness['activity']) => {
    switch (activity) {
      case 'viewing':
        return '👁️';
      case 'editing':
        return '✏️';
      case 'commenting':
        return '💬';
      default:
        return '👁️';
    }
  };

  const getActivityText = (activity: UserAwareness['activity']) => {
    switch (activity) {
      case 'viewing':
        return 'viewing';
      case 'editing':
        return 'editing';
      case 'commenting':
        return 'commenting on';
      default:
        return 'viewing';
    }
  };

  const getTimeAgo = (date: Date) => {
    const now = new Date();
    const seconds = Math.floor((now.getTime() - date.getTime()) / 1000);
    
    if (seconds < 10) return 'just now';
    if (seconds < 60) return `${seconds}s ago`;
    
    const minutes = Math.floor(seconds / 60);
    if (minutes < 60) return `${minutes}m ago`;
    
    return 'a while ago';
  };

  return (
    <div 
      className={`awareness-indicator awareness-indicator--${position} ${className}`}
      onMouseEnter={() => setIsExpanded(true)}
      onMouseLeave={() => setIsExpanded(false)}
    >
      <div className="awareness-indicator__badge">
        <div className="awareness-indicator__avatars">
          {recentActivity.slice(0, 3).map((user) => (
            <div
              key={user.userId}
              className="awareness-indicator__avatar"
              style={{ backgroundColor: user.color }}
              title={`${user.userName} is ${getActivityText(user.activity)} this`}
            >
              <span className="awareness-indicator__activity-icon">
                {getActivityIcon(user.activity)}
              </span>
            </div>
          ))}
          {recentActivity.length > 3 && (
            <div className="awareness-indicator__more">
              +{recentActivity.length - 3}
            </div>
          )}
        </div>
        
        <div className="awareness-indicator__pulse" />
      </div>

      {isExpanded && (
        <div className="awareness-indicator__tooltip">
          <div className="awareness-indicator__tooltip-header">
            Active in this section
          </div>
          <div className="awareness-indicator__tooltip-users">
            {recentActivity.map((user) => (
              <div key={user.userId} className="awareness-indicator__tooltip-user">
                <div 
                  className="awareness-indicator__tooltip-avatar"
                  style={{ backgroundColor: user.color }}
                >
                  {user.userName.charAt(0).toUpperCase()}
                </div>
                <div className="awareness-indicator__tooltip-info">
                  <div className="awareness-indicator__tooltip-name">
                    {user.userName}
                  </div>
                  <div className="awareness-indicator__tooltip-activity">
                    {getActivityIcon(user.activity)} {getActivityText(user.activity)} • {getTimeAgo(user.lastActivity)}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
      
      <style jsx>{`
        .awareness-indicator {
          position: absolute;
          z-index: 100;
        }
        
        .awareness-indicator--top {
          top: -30px;
          right: 0;
        }
        
        .awareness-indicator--bottom {
          bottom: -30px;
          right: 0;
        }
        
        .awareness-indicator--left {
          top: 0;
          left: -40px;
        }
        
        .awareness-indicator--right {
          top: 0;
          right: -40px;
        }
        
        .awareness-indicator__badge {
          position: relative;
          cursor: pointer;
        }
        
        .awareness-indicator__avatars {
          display: flex;
          align-items: center;
          gap: -8px;
        }
        
        .awareness-indicator__avatar {
          width: 24px;
          height: 24px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          border: 2px solid white;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
          transition: transform 0.2s ease;
        }
        
        .awareness-indicator__avatar:hover {
          transform: scale(1.1);
          z-index: 10;
        }
        
        .awareness-indicator__activity-icon {
          font-size: 10px;
        }
        
        .awareness-indicator__more {
          width: 24px;
          height: 24px;
          border-radius: 50%;
          background: #f0f0f0;
          border: 2px solid white;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 10px;
          font-weight: bold;
          color: #666;
        }
        
        .awareness-indicator__pulse {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          width: 40px;
          height: 40px;
          border-radius: 50%;
          background: rgba(78, 205, 196, 0.3);
          animation: pulse 2s infinite;
          pointer-events: none;
        }
        
        @keyframes pulse {
          0% {
            transform: translate(-50%, -50%) scale(0.8);
            opacity: 1;
          }
          100% {
            transform: translate(-50%, -50%) scale(1.5);
            opacity: 0;
          }
        }
        
        .awareness-indicator__tooltip {
          position: absolute;
          top: 100%;
          right: 0;
          margin-top: 8px;
          background: white;
          border: 1px solid #e0e0e0;
          border-radius: 8px;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
          padding: 12px;
          min-width: 250px;
          animation: fadeIn 0.2s ease;
        }
        
        @keyframes fadeIn {
          from {
            opacity: 0;
            transform: translateY(-4px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
        
        .awareness-indicator__tooltip-header {
          font-size: 12px;
          font-weight: bold;
          color: #666;
          margin-bottom: 8px;
          text-transform: uppercase;
          letter-spacing: 0.5px;
        }
        
        .awareness-indicator__tooltip-users {
          display: flex;
          flex-direction: column;
          gap: 8px;
        }
        
        .awareness-indicator__tooltip-user {
          display: flex;
          align-items: center;
          gap: 8px;
        }
        
        .awareness-indicator__tooltip-avatar {
          width: 28px;
          height: 28px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          font-size: 12px;
          font-weight: bold;
          flex-shrink: 0;
        }
        
        .awareness-indicator__tooltip-info {
          flex: 1;
          min-width: 0;
        }
        
        .awareness-indicator__tooltip-name {
          font-size: 13px;
          font-weight: 600;
          color: #333;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        
        .awareness-indicator__tooltip-activity {
          font-size: 11px;
          color: #666;
          margin-top: 2px;
        }
      `}</style>
    </div>
  );
};