import {
  Message,
  MessageContent,
  MessageResponse,
} from "@code/ui/components/ai-elements/message";
import {
  MobileChatBubble,
  MobileChatMessage,
} from "@code/ui/components/mobile-chat";
import type { ReactNode } from "react";

import { getMessageText, isMessageStreaming } from "@/lib/chat/transforms";
import type { ChatMessageProps } from "@/lib/chat/types";

import { AssistantIdentity } from "./assistant-identity";
import { ChatToolCall } from "./chat-tool-call";

export const ChatMessage = ({ message }: ChatMessageProps) => {
  const isUser = message.role === "user";
  const isStreaming = isMessageStreaming(message);
  const text = getMessageText(message);

  if (message.parts.length === 0 && !isStreaming) {
    return null;
  }

  let content: ReactNode = text;
  if (!isUser) {
    content = text ? (
      <MessageResponse
        caret={isStreaming ? "block" : undefined}
        className="chat-markdown min-w-0"
        isAnimating={isStreaming}
      >
        {text}
      </MessageResponse>
    ) : (
      <div className="thinking-line" aria-label="Zopu is preparing a response">
        <span />
        <span />
        <span />
      </div>
    );
  }

  const sender = isUser ? "user" : "assistant";

  return (
    <Message className="max-w-full gap-0" from={message.role}>
      <MessageContent className="w-full max-w-none gap-0 overflow-visible rounded-none bg-transparent p-0 group-[.is-user]:rounded-none group-[.is-user]:bg-transparent group-[.is-user]:p-0">
        <MobileChatMessage className="chat-message" sender={sender}>
          <div className={isUser ? "max-w-full" : "w-full min-w-0"}>
            {!isUser && (
              <AssistantIdentity state={isStreaming ? "writing" : undefined} />
            )}
            <MobileChatBubble
              className={isUser ? "whitespace-pre-wrap" : undefined}
              sender={sender}
            >
              {message.parts.map((part) =>
                part.type === "dynamic-tool" ? (
                  <ChatToolCall key={part.toolCallId} part={part} />
                ) : null
              )}
              {content}
            </MobileChatBubble>
          </div>
        </MobileChatMessage>
      </MessageContent>
    </Message>
  );
};
