import { useEffect, useMemo, useRef, useState } from 'react';
import type { User } from './types';
import { UserCardProps, CardType } from './types';
import AvatarOnlyCard from './Cards/avatar-only';
import DetailedCard from './Cards';
import DialogContainer from './Container/dialog';
import CardContainer from './Container/card';
import Avatar from '../Avatar';
import { getUserByDid, isUserDid } from './utils';

// 创建仅显示名称首字母的头像
export function createNameOnlyAvatar(user: User) {
  if (!user) return null;

  // 使用全名或邮箱前缀作为显示内容
  let content = '';
  if (user.fullName) {
    // 提取名称首字母
    content = user.fullName.charAt(0).toUpperCase();
  } else if (user.email) {
    // 使用邮箱前缀首字母
    content = user.email.split('@')[0].charAt(0).toUpperCase();
  } else {
    // 如果都没有，使用DID的第一个字符
    content = user.did ? user.did.charAt(0).toUpperCase() : '?';
  }

  return content;
}

// UserCard组件入口
function UserCard(props: UserCardProps) {
  const { cardType = CardType.Detailed, showHoverCard } = props;

  // 计算是否显示悬停卡片
  // 默认规则：AvatarOnly模式下默认显示悬停卡片，Detailed模式下默认不显示
  const shouldShowHoverCard = showHoverCard !== undefined ? showHoverCard : cardType === CardType.AvatarOnly;

  const containerRef = useRef<HTMLDivElement>(null);
  const [user, setUser] = useState<User | null>(() => props.user || null);

  useEffect(() => {
    let isSubscribed = true;
    if (props.user) {
      setUser(props.user);
    } else if (props.did && isUserDid(props.did) && !props.user) {
      getUserByDid(props.did).then((_user) => {
        if (isSubscribed) {
          setUser(_user || { fullName: 'Anonymous', did: props.did as string, avatar: '' });
        }
      });
    }
    return () => {
      isSubscribed = false;
    };
  }, [props.did, props.user]);

  // 补全 avatar 的 imageFilter 信息，以提高性能
  const userInfo = useMemo(() => {
    if (!user) {
      return null;
    }

    const { avatar = '', ...rest } = user;
    if (avatar) {
      const avatarParam = avatar.split('?')[1] || '';
      return {
        ...rest,
        avatar: avatarParam ? avatar : `${avatar}?imageFilter=resize&w=48&h=48`,
      };
    }
    return user;
  }, [user]);

  // 如果不存在，则使用 did 渲染头像
  if (!userInfo) {
    return <Avatar did={props.did} size={props.avatarSize} useProxyFallback {...props.avatarProps} />;
  }

  // user 存在，则使用 user 渲染头像
  // 渲染卡片内容（用于Tooltip）
  const renderCardContent = () => {
    return (
      <DialogContainer sx={props.popupSx}>
        <DetailedCard
          {...props}
          shouldShowHoverCard={false}
          user={userInfo!}
          avatarProps={props.popupAvatarProps}
          shortenLabelProps={props.popupShortenLabelProps || props.shortenLabelProps}
          renderFields={props.popupRenderFields}
          renderName={props.popupRenderName}
          infoType={props.popupInfoType || props.infoType}
          didProps={props.popupDidProps || props.didProps}
          showDid={props.popupShowDid || props.showDid}
        />
      </DialogContainer>
    );
  };

  // 根据卡片类型选择合适的组件
  if (cardType === CardType.AvatarOnly) {
    return (
      <AvatarOnlyCard
        {...props}
        shouldShowHoverCard={shouldShowHoverCard}
        renderCardContent={renderCardContent}
        user={userInfo!}
      />
    );
  }

  // 详细卡片模式
  return (
    <CardContainer containerRef={containerRef} cardType={cardType} sx={props.sx}>
      <DetailedCard
        {...props}
        shouldShowHoverCard={shouldShowHoverCard}
        renderCardContent={renderCardContent}
        user={userInfo!}
      />
    </CardContainer>
  );
}

export default UserCard;
