import { memo, useMemo } from "react";
import { TicketMessage } from "@frontend/kitui";
import ChatMessage from "./ChatMessage";
import ChatImage from "./ChatImage";
import ChatVideo from "./ChatVideo";
import ChatDocument from "./ChatDocument";
import { ACCEPT_SEND_MEDIA_TYPES_MAP } from "@utils/checkAcceptableMediaType";

interface ChatMessageRendererProps {
  message: TicketMessage;
  isSelf: boolean;
}

const ChatMessageRenderer = memo(({ message, isSelf }: ChatMessageRendererProps) => {
  const fileType = useMemo(() => {
    if (!message.files?.length) return null;

    const fileName = message.files[0].toLowerCase();
    
    if (ACCEPT_SEND_MEDIA_TYPES_MAP.video.some(fileType => fileName.endsWith(fileType))) {
      return 'video';
    }
    
    if (ACCEPT_SEND_MEDIA_TYPES_MAP.picture.some(fileType => fileName.endsWith(fileType))) {
      return 'image';
    }
    
    if (ACCEPT_SEND_MEDIA_TYPES_MAP.document.some(fileType => fileName.endsWith(fileType))) {
      return 'document';
    }
    
    return null;
  }, [message.files]);

  // Если есть файлы и определён тип
  if (message.files?.length > 0 && fileType) {
    const commonProps = {
      unAuthenticated: true,
      key: message.id,
      file: message.files[0],
      createdAt: message.created_at,
      isSelf,
    };

    switch (fileType) {
      case 'image':
        return <ChatImage {...commonProps} />;
      case 'video':
        return <ChatVideo {...commonProps} />;
      case 'document':
        return <ChatDocument {...commonProps} />;
      default:
        break;
    }
  }

  // Текстовое сообщение
  return (
    <ChatMessage
      unAuthenticated
      text={message.message}
      createdAt={message.created_at}
      isSelf={isSelf}
    />
  );
});

ChatMessageRenderer.displayName = 'ChatMessageRenderer';

export default ChatMessageRenderer; 