import { MessageItem as MessageItemType, MessageType } from "@openim/wasm-client-sdk";
import clsx from "clsx";
import { FC, memo } from "react";

import OIMAvatar from "@/components/OIMAvatar";

import CatchMessageRender from "./CatchMsgRenderer";
import FileMessageRender from "./FileMessageRender";
import MediaMessageRender from "./MediaMessageRender";
import styles from "./message-item.module.scss";
import MessageItemErrorBoundary from "./MessageItemErrorBoundary";
import MessageSuffix from "./MessageSuffix";
import SoundMessageRender from "./SoundMessageRender";
import TextMessageRender from "./TextMessageRender";

export interface IMessageItemProps {
  message: MessageItemType;
  isSender: boolean;
  disabled?: boolean;
  conversationID?: string;
  messageUpdateFlag?: string;
}

const components: Record<number, FC<IMessageItemProps>> = {
  [MessageType.TextMessage]: TextMessageRender,
  [MessageType.PictureMessage]: MediaMessageRender,
  [MessageType.FileMessage]: FileMessageRender,
  [MessageType.VoiceMessage]: SoundMessageRender,
};

const MessageItem: FC<IMessageItemProps> = ({
  message,
  disabled,
  isSender,
  conversationID,
}) => {
  const MessageRenderComponent = components[message.contentType] || CatchMessageRender;
  const isGroupMessage = Boolean(message.groupID);
  const showNickname = isGroupMessage && !isSender;

  return (
    <div
      id={`chat_${message.clientMsgID}`}
      className={clsx("relative flex select-text px-5 py-2")}
    >
      <div
        className={clsx(
          styles["message-container"],
          isSender && styles["message-container-sender"],
        )}
      >
        <OIMAvatar
          className="rounded-lg"
          size={40}
          src={message.senderFaceUrl}
          text={message.senderNickname}
        />

        <div className={styles["message-wrap"]}>
          {showNickname && (
            <div className={styles["message-profile"]}>
              <div
                title={message.senderNickname}
                className="max-w-[60%] truncate text-xs text-[var(--sub-text)]"
              >
                {message.senderNickname}
              </div>
            </div>
          )}

          <div className={styles["menu-wrap"]}>
            <MessageItemErrorBoundary message={message}>
              <MessageRenderComponent
                message={message}
                isSender={isSender}
                disabled={disabled}
              />
            </MessageItemErrorBoundary>

            <MessageSuffix
              message={message}
              isSender={isSender}
              disabled={false}
              conversationID={conversationID}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default memo(MessageItem);
