import { Avatar } from "@mui/material";
import { MatrixApiMedia } from "../../api/matrix/MatrixApiMedia";
import type { UsersMap } from "../../api/matrix/MatrixApiProfile";
import {
  mainRoomMember,
  roomName,
  type Room,
} from "../../api/matrix/MatrixApiRoom";
import { useUserInfo } from "../dashboard/BaseAuthenticatedPage";

export function RoomIcon(p: {
  room: Room;
  users: UsersMap;
}): React.ReactElement {
  const user = useUserInfo();

  let url = p.room.avatar;

  if (!url) {
    const member = mainRoomMember(user.info, p.room);
    if (member) url = p.users.get(member)?.avatar;
  }
  const name = roomName(user.info, p.room, p.users);

  return (
    <Avatar
      variant={p.room.is_space ? "square" : undefined}
      src={url ? MatrixApiMedia.MediaURL(url, true) : undefined}
    >
      {name.slice(0, 1)}
    </Avatar>
  );
}
