import React from 'react';
import { Avatar, Text } from 'folds';
import { Room } from 'matrix-js-sdk';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { getMemberAvatarMxc, getMemberDisplayName } from '../../utils/room';
import { UserAvatar } from '../../components/user-avatar';
import { mxcUrlToHttp } from '../../utils/matrix';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
import * as theme from './forumTheme.css';

function matrixUserServer(userId: string): string {
  const parts = userId.split(':');
  return parts.length > 1 ? parts[1] : '';
}

function matrixUserLocalpart(userId: string): string {
  return userId.split(':')[0]?.replace('@', '') || userId;
}

type ForumAuthorIdentityProps = {
  room: Room | null;
  sender: string;
  displayName?: string;
  wrapTag?: 'strong' | 'span';
  compact?: boolean;
};

/** matrixsso `author-identity` chip (avatar + name + server). */
export function ForumAuthorIdentity({
  room,
  sender,
  displayName,
  wrapTag: WrapTag = 'strong',
  compact = false,
}: ForumAuthorIdentityProps) {
  const mx = useMatrixClient();
  const useAuthentication = useMediaAuthentication();
  const mxc = room ? getMemberAvatarMxc(room, sender) : undefined;
  const avatarUrl = mxc
    ? mxcUrlToHttp(mx, mxc, useAuthentication, compact ? 36 : 48, compact ? 36 : 48, 'crop') ??
      undefined
    : undefined;
  const name =
    displayName || (room ? getMemberDisplayName(room, sender) : undefined) || matrixUserLocalpart(sender);
  const server = matrixUserServer(sender);

  const identityClass = compact
    ? `${theme.ForumAuthorIdentity} ${theme.ForumAuthorIdentityCompact}`
    : theme.ForumAuthorIdentity;
  const avatarClass = compact ? theme.ForumAuthorAvatarCompact : theme.ForumAuthorAvatar;

  return (
    <div className={identityClass}>
      <span className={avatarClass} aria-hidden>
        <Avatar size="200" radii="300" shrink="No">
          <UserAvatar
            userId={sender}
            src={avatarUrl}
            alt={name}
            renderFallback={() => (
              <Text size="L400">{name.slice(0, 1).toUpperCase()}</Text>
            )}
          />
        </Avatar>
      </span>
      <span className={theme.ForumAuthorMeta}>
        <WrapTag className={theme.ForumSenderLabel} title={sender}>
          {name}
        </WrapTag>
        {server ? <span className={theme.ForumAuthorServer}>{server}</span> : null}
      </span>
    </div>
  );
}
