import React from 'react';
import { format } from 'date-fns';

export interface Message {
  id: string;
  role: 'user' | 'assistant' | 'system';
  content: string;
  timestamp: Date;
  isStreaming?: boolean;
  tools_used?: string[];
}

interface ChatMessageProps {
  message: Message;
  isLast?: boolean;
  onRetry?: () => void;
  onFeedback?: (positive: boolean) => void;
  onSignalExecute?: (signal: unknown) => void;
  compact?: boolean;
}

export const ChatMessage: React.FC<ChatMessageProps> = ({
  message,
  isLast: _isLast,
  onRetry: _onRetry,
  onFeedback: _onFeedback,
  onSignalExecute: _onSignalExecute,
  compact: _compact,
}) => {
  const isUser = message.role === 'user';
  const isSystem = message.role === 'system';

  if (isSystem) {
    return (
      <div className="flex justify-center my-2">
        <span className="text-xs text-gray-500 bg-gray-100 dark:bg-gray-800 px-3 py-1 rounded-full">
          {message.content}
        </span>
      </div>
    );
  }

  return (
    <div className={`flex ${isUser ? 'justify-end' : 'justify-start'} mb-4`}>
      <div
        className={`max-w-[80%] rounded-2xl px-4 py-3 ${
          isUser
            ? 'bg-primary-600 text-white rounded-br-sm'
            : 'bg-gray-100 dark:bg-gray-800 text-gray-900 dark:text-white rounded-bl-sm'
        }`}
      >
        {/* Avatar and name */}
        <div className="flex items-center gap-2 mb-1">
          <div
            className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold ${
              isUser
                ? 'bg-primary-700 text-white'
                : 'bg-gradient-to-r from-cyan-500 to-blue-500 text-white'
            }`}
          >
            {isUser ? 'U' : 'AI'}
          </div>
          <span className={`text-xs ${isUser ? 'text-primary-200' : 'text-gray-500'}`}>
            {isUser ? 'You' : 'OrbiQuant AI'}
          </span>
          <span className={`text-xs ${isUser ? 'text-primary-300' : 'text-gray-400'}`}>
            {format(message.timestamp, 'HH:mm')}
          </span>
        </div>

        {/* Message content */}
        <div className="whitespace-pre-wrap break-words">
          {message.content}
          {message.isStreaming && (
            <span className="inline-block w-2 h-4 ml-1 bg-current animate-pulse" />
          )}
        </div>

        {/* Tools used badge */}
        {message.tools_used && message.tools_used.length > 0 && (
          <div className="flex flex-wrap gap-1 mt-2">
            {message.tools_used.map((tool) => (
              <span
                key={tool}
                className="text-xs px-2 py-0.5 rounded-full bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300"
              >
                {tool}
              </span>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default ChatMessage;
