import { memo } from 'react';
import { Avatar } from 'antd';
import type { NodeProps } from '@xyflow/react';

const ROLE_BG: Record<string, string> = {
  SUPER_ADMIN: '#f5222d',
  INFLUENCE_ADMIN: '#1890ff',
  MAP_ADMIN: '#52c41a',
  USER: '#722ed1',
  TEMP: '#faad14',
};

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

export interface SocialUserNodeData {
  name: string | null;
  email: string;
  role: string;
  isOnline: boolean;
  friendCount: number;
  achievementCount: number;
  groups: string[];
  [key: string]: unknown;
}

function SocialUserNodeComponent({ data }: NodeProps) {
  const d = data as SocialUserNodeData;
  // Size avatar by friend count: min 28, max 56
  const avatarSize = Math.min(56, Math.max(28, 28 + (d.friendCount ?? 0) * 2));
  const bgColor = ROLE_BG[d.role] || '#722ed1';

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        gap: 4,
        cursor: 'pointer',
        padding: 4,
      }}
    >
      <div
        style={{
          borderRadius: '50%',
          border: d.isOnline ? '3px solid #52c41a' : '2px solid rgba(255,255,255,0.2)',
          padding: 2,
        }}
      >
        <Avatar
          size={avatarSize}
          style={{
            backgroundColor: bgColor,
            fontWeight: 600,
            fontSize: Math.max(11, avatarSize * 0.35),
          }}
        >
          {getInitials(d.name, d.email)}
        </Avatar>
      </div>
      <div
        style={{
          fontSize: 10,
          color: '#fff',
          maxWidth: 80,
          textAlign: 'center',
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          lineHeight: '14px',
        }}
      >
        {d.name || d.email.split('@')[0]}
      </div>
    </div>
  );
}

export const SocialUserNode = memo(SocialUserNodeComponent);
