import React from 'react';

import { Badge } from '@/components/UI';

import MessageTool from './MessageTool';
import type { DebugTranscriptTextRow, DebugTranscriptToolRow } from './types';

const TranscriptAssistantBlock: React.FC<{
  message?: DebugTranscriptTextRow;
  tools: DebugTranscriptToolRow[];
}> = ({ message, tools }) => {
  const isStreaming = Boolean(message?.isStreaming) || tools.some((tool) => tool.status === 'pending');

  return (
    <div className="flex justify-start">
      <div className="w-full max-w-[85%] rounded-lg border border-white/10 bg-card px-3 py-2 text-sm text-foreground shadow-sm">
        <div className="mb-1 flex flex-wrap items-center gap-1.5">
          <span className="text-[10px] uppercase tracking-wider opacity-70">AI</span>
          {typeof message?.ttfbMs === 'number' && Number.isFinite(message.ttfbMs) && (
            <Badge
              variant="outline"
              className="border-cyan-300/40 bg-cyan-500/10 px-1.5 py-0.5 text-[10px] text-cyan-200"
            >
              TTFB {Math.round(message.ttfbMs)}ms
            </Badge>
          )}
          {tools.length > 0 && (
            <Badge variant="outline" className="border-white/15 bg-black/10 px-1.5 py-0.5 text-[10px]">
              {tools.length} tool{tools.length > 1 ? 's' : ''}
            </Badge>
          )}
          {isStreaming && <span className="inline-flex h-2 w-2 animate-pulse rounded-full bg-primary/80" />}
        </div>

        {message?.text ? (
          <div className="whitespace-pre-wrap break-words">{message.text}</div>
        ) : null}

        {tools.length > 0 && (
          <div className={message?.text ? 'mt-3 border-t border-white/10 pt-3' : 'mt-1'}>
            <div className="space-y-2">
              {tools.map((tool) => (
                <MessageTool key={tool.id} row={tool} nested />
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default React.memo(TranscriptAssistantBlock);
