import React from 'react'
import { cn } from '@/lib/utils'
import type { Message } from '@/store/useChatStore'
import { ToolStatusIndicator } from './ToolStatusIndicator'
import { MarkdownRenderer } from './MarkdownRenderer'
import { Sparkles, User } from 'lucide-react'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'

interface ChatBubbleProps {
  message: Message
}

export const ChatBubble = React.memo(function ChatBubble({ message }: ChatBubbleProps) {
  const isAgent = message.role === 'agent'

  return (
    <div
      className={cn(
        'flex w-full my-4 max-w-3xl mx-auto items-start gap-3 group animate-in fade-in-50 duration-200',
        isAgent ? 'justify-start' : 'justify-end'
      )}
    >
      {isAgent && (
        <div className="w-8 h-8 rounded-full bg-primary/10 border border-primary/20 flex items-center justify-center text-primary shrink-0 mt-0.5 shadow-sm">
          <Sparkles className="w-4 h-4 text-primary animate-pulse" />
        </div>
      )}

      <div className={cn('flex flex-col gap-1.5 min-w-0', isAgent ? 'flex-1' : 'max-w-[80%]')}>
        {isAgent && message.toolStatus && (
          <ToolStatusIndicator toolName={message.toolStatus} />
        )}

        <div
          className={cn(
            'text-sm transition-all duration-200 overflow-hidden',
            isAgent
              ? 'text-foreground leading-relaxed py-1 px-1'
              : 'bg-secondary border border-border/80 text-secondary-foreground font-normal px-5 py-3 rounded-3xl self-end shadow-sm'
          )}
        >
          {isAgent ? (
            <MarkdownRenderer content={message.content} isStreaming={message.isStreaming} />
          ) : (
            <div className="whitespace-pre-wrap leading-relaxed">{message.content}</div>
          )}
        </div>
      </div>

      {!isAgent && (
        <Avatar className="w-8 h-8 border border-border/80 shrink-0 bg-muted shadow-sm">
          <AvatarFallback className="bg-muted text-muted-foreground font-semibold text-xs">
            <User className="w-4 h-4" />
          </AvatarFallback>
        </Avatar>
      )}
    </div>
  )
})

