import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '../utils/cn';

const chatBubbleVariants = cva(
  'relative max-w-[85%] rounded-2xl px-4 py-3 text-sm leading-relaxed',
  {
    variants: {
      role: {
        user: 'ml-auto bg-[var(--accent)] text-[var(--accent-foreground)] rounded-br-sm',
        assistant: 'mr-auto bg-[var(--surface-200)] text-[var(--text-primary)] rounded-bl-sm',
        system: 'mx-auto bg-[var(--surface-100)] text-[var(--text-secondary)] text-xs italic max-w-[90%]',
      },
    },
    defaultVariants: {
      role: 'assistant',
    },
  }
);

export interface ChatBubbleProps
  extends Omit<React.HTMLAttributes<HTMLDivElement>, 'role'>,
    VariantProps<typeof chatBubbleVariants> {
  content: string;
  timestamp?: Date;
  avatar?: string;
  isStreaming?: boolean;
}

const ChatBubble = React.forwardRef<HTMLDivElement, ChatBubbleProps>(
  ({ className, role, content, timestamp, avatar, isStreaming, ...props }, ref) => {
    const isUser = role === 'user';

    return (
      <div
        ref={ref}
        className={cn(
          'flex items-end gap-2',
          isUser ? 'flex-row-reverse' : 'flex-row',
          className
        )}
        {...props}
      >
        {avatar && role !== 'system' && (
          <div className="flex-shrink-0 w-8 h-8 rounded-full bg-[var(--surface-300)] overflow-hidden">
            <img src={avatar} alt="" className="w-full h-full object-cover" />
          </div>
        )}

        <div className="flex flex-col gap-1">
          <div className={cn(chatBubbleVariants({ role }))}>
            <span className="whitespace-pre-wrap">{content}</span>
            {isStreaming && (
              <span className="inline-block w-2 h-4 ml-1 bg-current animate-pulse" />
            )}
          </div>

          {timestamp && (
            <span
              className={cn(
                'text-xs text-[var(--text-muted)]',
                isUser ? 'text-right' : 'text-left'
              )}
            >
              {timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
            </span>
          )}
        </div>
      </div>
    );
  }
);
ChatBubble.displayName = 'ChatBubble';

export { ChatBubble, chatBubbleVariants };
