'use client';

import React from 'react';

export interface UserAvatarProps {
  /** 用户头像 URL */
  avatar?: string | null;
  /** 用户显示名称（用于提取首字母） */
  displayName: string;
  /** 头像尺寸（像素） */
  size?: number | 'sm' | 'md' | 'lg' | 'xl';
  /** 自定义类名 */
  className?: string;
  /** 背景颜色（默认为蓝色渐变） */
  backgroundColor?: string;
  /** 文字颜色（默认为白色） */
  textColor?: string;
  /** 是否显示圆形 */
  rounded?: boolean;
  /** 点击事件 */
  onClick?: () => void;
}

/**
 * 通用用户头像组件
 * 
 * @description
 * - 如果有头像 URL，显示头像图片
 * - 如果没有头像，显示用户名的首字母（FirstName 和 LastName 的首字母）
 * - 支持多种尺寸预设和自定义尺寸
 * - 支持自定义颜色和样式
 * 
 * @example
 * ```tsx
 * // 基础用法
 * <UserAvatar displayName="John Doe" />
 * 
 * // 带头像
 * <UserAvatar avatar="https://..." displayName="John Doe" />
 * 
 * // 不同尺寸
 * <UserAvatar displayName="John Doe" size="sm" />
 * <UserAvatar displayName="John Doe" size={64} />
 * 
 * // 自定义颜色
 * <UserAvatar 
 *   displayName="John Doe" 
 *   backgroundColor="#ff6b6b" 
 *   textColor="#fff" 
 * />
 * ```
 */
export default function UserAvatar({
  avatar,
  displayName,
  size = 'md',
  className = '',
  backgroundColor,
  textColor = 'white',
  rounded = true,
  onClick,
}: UserAvatarProps) {
  // 尺寸映射
  const sizeMap = {
    sm: 32,   // 小尺寸（列表中使用）
    md: 40,   // 中等尺寸（默认）
    lg: 64,   // 大尺寸（详情页）
    xl: 96,   // 超大尺寸
  };

  // 获取实际像素尺寸
  const actualSize = typeof size === 'number' ? size : sizeMap[size];

  // 字体大小（根据头像大小动态调整）
  const fontSize = actualSize * 0.4;

  /**
   * 提取用户名的首字母
   * 支持中文和英文名字
   * 
   * 规则：
   * 1. 如果是英文名（包含空格），取第一个和最后一个单词的首字母，如 "John Doe" -> "JD"
   * 2. 如果是中文名或单个单词，取前两个字符，如 "张三" -> "张三"，"John" -> "JO"
   * 3. 如果只有一个字符，返回该字符
   */
  const getInitials = (name: string): string => {
    if (!name) return 'U';

    const trimmedName = name.trim();
    
    // 如果包含空格，认为是 FirstName LastName 格式
    if (trimmedName.includes(' ')) {
      const parts = trimmedName.split(' ').filter(part => part.length > 0);
      if (parts.length >= 2) {
        // 取第一个和最后一个单词的首字母
        return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
      }
    }
    
    // 单个单词或中文名：取前两个字符
    if (trimmedName.length >= 2) {
      return trimmedName.substring(0, 2).toUpperCase();
    }
    
    // 只有一个字符
    return trimmedName[0].toUpperCase();
  };

  const initials = getInitials(displayName);

  // 根据用户名生成一致的颜色（飞书风格）
  const generateColorFromName = (name: string): string => {
    // 飞书风格的柔和颜色（纯色，不使用渐变）
    const colors = [
      '#5B8FF9', // 柔和蓝
      '#5AD8A6', // 柔和绿
      '#5D7092', // 柔和灰蓝
      '#F6BD16', // 柔和黄
      '#E86452', // 柔和红
      '#6DC8EC', // 柔和青
      '#945FB9', // 柔和紫
      '#FF9D4D', // 柔和橙
      '#269A99', // 柔和青绿
      '#FF99C3', // 柔和粉
    ];

    // 根据名字生成哈希值
    let hash = 0;
    for (let i = 0; i < name.length; i++) {
      hash = name.charCodeAt(i) + ((hash << 5) - hash);
    }
    
    const index = Math.abs(hash) % colors.length;
    return colors[index];
  };

  const defaultBackground = backgroundColor || generateColorFromName(displayName);
  
  // 基础样式
  const baseStyle: React.CSSProperties = {
    width: actualSize,
    height: actualSize,
    fontSize: `${fontSize}px`,
    borderRadius: rounded ? '50%' : '8px',
    flexShrink: 0,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    fontWeight: 600,
    color: textColor,
    cursor: onClick ? 'pointer' : 'default',
    userSelect: 'none',
  };

  // 如果有头像
  if (avatar) {
    return (
      <div
        className={className}
        style={{
          ...baseStyle,
          backgroundImage: `url(${avatar})`,
          backgroundSize: 'cover',
          backgroundPosition: 'center',
        }}
        onClick={onClick}
        title={displayName}
      />
    );
  }

  // 没有头像，显示首字母
  return (
    <div
      className={className}
      style={{
        ...baseStyle,
        backgroundColor: defaultBackground,
      }}
      onClick={onClick}
      title={displayName}
    >
      {initials}
    </div>
  );
}

/**
 * 根据用户名生成一致的颜色（飞书风格）
 * 可用于为不同用户生成不同的头像背景色
 */
export function getUserAvatarColor(displayName: string): string {
  const colors = [
    '#5B8FF9', // 柔和蓝
    '#5AD8A6', // 柔和绿
    '#5D7092', // 柔和灰蓝
    '#F6BD16', // 柔和黄
    '#E86452', // 柔和红
    '#6DC8EC', // 柔和青
    '#945FB9', // 柔和紫
    '#FF9D4D', // 柔和橙
    '#269A99', // 柔和青绿
    '#FF99C3', // 柔和粉
  ];

  // 根据名字生成哈希值
  let hash = 0;
  for (let i = 0; i < displayName.length; i++) {
    hash = displayName.charCodeAt(i) + ((hash << 5) - hash);
  }
  
  const index = Math.abs(hash) % colors.length;
  return colors[index];
}

