import { Message } from '@/lib/db';

interface MessageBubbleProps {
  message: Message;
  showDateSeparator?: boolean;
  dateLabel?: string;
}

/* ── Relative timestamp ─────────────────────────────────────────────────── */
function getRelativeTime(unixSeconds: number): string {
  const now = Date.now() / 1000;
  const diff = now - unixSeconds;

  if (diff < 60) return 'ahora';
  if (diff < 3600) return `hace ${Math.floor(diff / 60)} min`;
  if (diff < 86400) {
    return new Date(unixSeconds * 1000).toLocaleTimeString('es-MX', { hour: '2-digit', minute: '2-digit' });
  }
  if (diff < 172800) return 'ayer';
  return new Date(unixSeconds * 1000).toLocaleDateString('es-MX', { day: 'numeric', month: 'short' });
}

export function getDateLabel(unixSeconds: number): string {
  const now = new Date();
  const date = new Date(unixSeconds * 1000);
  const diffDays = Math.floor((now.getTime() - date.getTime()) / 86400000);

  if (diffDays === 0) return 'Hoy';
  if (diffDays === 1) return 'Ayer';
  if (diffDays < 7) {
    return date.toLocaleDateString('es-MX', { weekday: 'long' });
  }
  return date.toLocaleDateString('es-MX', { day: 'numeric', month: 'long', year: diffDays > 365 ? 'numeric' : undefined });
}

export function isSameDay(a: number, b: number): boolean {
  const dateA = new Date(a * 1000);
  const dateB = new Date(b * 1000);
  return (
    dateA.getFullYear() === dateB.getFullYear() &&
    dateA.getMonth() === dateB.getMonth() &&
    dateA.getDate() === dateB.getDate()
  );
}

export function MessageBubble({ message, showDateSeparator, dateLabel }: MessageBubbleProps) {
  const isUser = message.role === 'user';
  const isAssistant = message.role === 'assistant';
  const isHuman = message.role === 'human';

  const timeStr = getRelativeTime(message.created_at);
  const fullTime = new Date(message.created_at * 1000).toLocaleString('es-MX', {
    weekday: 'short', day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit',
  });

  // Format content: convert newlines to <br>
  const lines = message.content.split('\n');

  return (
    <>
      {/* Date Separator */}
      {showDateSeparator && dateLabel && (
        <div className="day-label">
          <span>{dateLabel}</span>
        </div>
      )}

      <div className={`msg-row ${isUser ? 'in' : 'out'}`}>
        <div
          className={`bubble ${
            isUser ? 'in' : isAssistant ? 'out-ai' : 'out-human'
          }`}
        >
          {/* Role Label (AI or Human only) */}
          {(isAssistant || isHuman) && (
            <div className={`bubble-tag ${isAssistant ? 'ai' : 'human'}`}>
              {isAssistant ? (
                <>
                  <svg width="11" height="11" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24" style={{ display: 'inline', marginRight: '4px', verticalAlign: 'middle' }}>
                    <path strokeLinecap="round" strokeLinejoin="round"
                      d="M9.75 3.104v5.714a2.25 2.25 0 01-.659 1.591L5 14.5M9.75 3.104c-.251.023-.501.05-.75.082m.75-.082a24.301 24.301 0 014.5 0m0 0v5.714c0 .597.237 1.17.659 1.591L19.8 14.5M14.25 3.104c.251.023.501.05.75.082M19.8 14.5l-2.147 2.148a.75.75 0 01-.53.22H6.877a.75.75 0 01-.53-.22L4.2 14.5m15.6 0a2.25 2.25 0 00.659-1.591V8.5" />
                  </svg>
                  Bot IA
                </>
              ) : (
                <>
                  <svg width="11" height="11" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24" style={{ display: 'inline', marginRight: '4px', verticalAlign: 'middle' }}>
                    <path strokeLinecap="round" strokeLinejoin="round"
                      d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
                  </svg>
                  Agente
                </>
              )}
            </div>
          )}

          {/* Message Content with line breaks */}
          <p style={{ color: 'var(--text)', whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
            {lines.map((line, i) => (
              <span key={i}>
                {line}
                {i < lines.length - 1 && <br />}
              </span>
            ))}
          </p>

          {/* Timestamp */}
          <div className="bubble-time" title={fullTime}>
            {timeStr}
          </div>
        </div>
      </div>
    </>
  );
}
