import React from 'react';
import { Box, Avatar as MaterialAvatar } from '@mui/material';
import Avatar from '../Avatar';
import { User, UserCardProps } from './types';
import { createNameOnlyAvatar } from './utils';

// 渲染头像
export const renderAvatar = (
  user: User,
  avatarSize: number = 48,
  avatarProps: UserCardProps['avatarProps'] = undefined,
  onAvatarClick: UserCardProps['onAvatarClick'] = undefined,
  shouldShowHoverCard: boolean = false
) => {
  const onClick = (e: React.MouseEvent<HTMLDivElement>) => {
    onAvatarClick?.(user, e);
  };
  // 如果用户没有头像，则显示名称首字母头像
  if (!user.avatar) {
    const avatarContent = createNameOnlyAvatar(user);
    // 从 avatarProps 中提取 MUI 的 Avatar 支持的基本 props
    // className, style 等基本 React 属性
    const { className, style, alt } = avatarProps || {};

    return (
      <MaterialAvatar
        onClick={onClick}
        className={className}
        style={style}
        alt={alt}
        sx={{
          width: avatarSize,
          height: avatarSize,
          fontSize: avatarSize * 0.4,
          cursor: shouldShowHoverCard || onAvatarClick ? 'pointer' : 'default',
        }}
        variant="circular">
        {avatarContent}
      </MaterialAvatar>
    );
  }

  // 显示用户头像
  return (
    <Box
      className="user-card__avatar"
      sx={{
        display: 'flex',
      }}>
      <Avatar
        size={avatarSize}
        did={user.did}
        variant="circle"
        useProxyFallback
        style={{
          cursor: shouldShowHoverCard || onAvatarClick ? 'pointer' : 'default',
        }}
        onClick={onClick}
        src={user.avatar}
        alt={user.fullName || ''}
        {...(avatarProps || {})}
      />
    </Box>
  );
};

// 渲染右上角内容
export const renderTopRight = (
  renderTopRightContent: (() => React.ReactNode) | undefined,
  topRightMaxWidth: number = 120
) => {
  if (renderTopRightContent) {
    return (
      <Box sx={{ maxWidth: topRightMaxWidth }} className="user-card__top-right-content">
        {renderTopRightContent()}
      </Box>
    );
  }

  return null;
};
