import { Tooltip, Badge, theme } from 'antd';
import { WifiOutlined, DisconnectOutlined } from '@ant-design/icons';
import type { Collaborator } from '@/hooks/useDocsCollaboration';

interface CollaboratorAvatarsProps {
  collaborators: Collaborator[];
  connected: boolean;
}

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

export function CollaboratorAvatars({ collaborators, connected }: CollaboratorAvatarsProps) {
  const { token } = theme.useToken();

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
      {/* Connection status indicator */}
      <Tooltip title={connected ? 'Connected — real-time sync active' : 'Disconnected — reconnecting...'}>
        {connected ? (
          <WifiOutlined style={{ fontSize: 12, color: token.colorSuccess }} />
        ) : (
          <DisconnectOutlined style={{ fontSize: 12, color: token.colorError }} />
        )}
      </Tooltip>

      {/* Collaborator avatars */}
      {collaborators.map((c) => (
        <Tooltip key={c.clientId} title={c.name}>
          <div
            style={{
              width: 22,
              height: 22,
              borderRadius: '50%',
              background: c.color,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: 10,
              fontWeight: 600,
              color: '#fff',
              border: `2px solid ${token.colorBgContainer}`,
              cursor: 'default',
            }}
          >
            {getInitials(c.name)}
          </div>
        </Tooltip>
      ))}

      {/* Count badge when there are collaborators */}
      {collaborators.length > 0 && (
        <Badge
          count={collaborators.length}
          size="small"
          style={{ backgroundColor: token.colorPrimary }}
        />
      )}
    </div>
  );
}
