import { memo } from 'react';
import type { Message } from '@/app/lib/types';
import { AssistantMessage } from './AssistantMessage';
import { useT } from './ContentProvider';
import { DbIcon, UserIcon } from './icons';
import { ErrorNotice } from './ErrorNotice';
import { TypingDots } from './TypingDots';
import { cx, Timestamp } from './ui';

// Memoized: while one message streams or the user types, the rest of the conversation must not re-render.
export const ChatMessage = memo(function ChatMessage({ msg, isStreaming }: { msg: Message; isStreaming: boolean }) {
  const t = useT();
  const isUser = msg.role === 'user';
  return (
    <div className={cx('message-enter flex gap-2.5', isUser ? 'flex-row-reverse' : 'flex-row')}>

      {/* Avatar */}
      <div className={cx('mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-[50%]', isUser ? 'bg-user' : 'border border-edge-strong bg-tint')}>
        {isUser ? <UserIcon color="white" /> : <DbIcon size={13} color="var(--color-accent)" />}
      </div>

      {/* Bubble */}
      <div className={cx('flex max-w-[calc(100%-40px)] flex-col', isUser ? 'items-end' : 'items-start')}>
        {isUser ? (
          <>
            <div className="rounded-[16px_16px_4px_16px] bg-user px-4 py-2.5 text-[16px] leading-[1.65] text-white [box-shadow:var(--shadow-user-bubble)]">
              {msg.content}
            </div>
            {msg.timestamp && <Timestamp side="right" ts={msg.timestamp} />}
          </>
        ) : (
          <>
            {msg.interpretation && (
              <div className="mb-1.5 inline-flex max-w-full items-center gap-1.5 rounded-md border border-edge bg-tint px-2 py-0.5 text-[12px] text-muted" title={t('copy.understoodAsTitle')}>
                <span className="shrink-0 font-bold uppercase tracking-[0.1em]">{t('copy.understoodAs')}</span>
                <span className="truncate">{msg.interpretation.label}</span>
              </div>
            )}
            <div className={cx('w-full rounded-[16px_16px_16px_4px] border border-l-2 border-edge bg-surface px-4 py-3.5', msg.error ? 'border-l-danger' : 'border-l-accent')}>
              {msg.content === '' && isStreaming ? (
                <TypingDots />
              ) : (msg.content !== '' || !msg.error) && (
                <AssistantMessage content={msg.content} isStreaming={isStreaming} />
              )}
              {msg.error && <ErrorNotice spaced={msg.content !== ''}>{msg.error}</ErrorNotice>}
            </div>
            {msg.timestamp && (msg.content || msg.error) && <Timestamp side="left" ts={msg.timestamp} />}
          </>
        )}
      </div>
    </div>
  );
});
