import React, { useEffect, useRef } from 'react';
import { ChatUiMessage } from '../../types/chatAssistant';
import ChatMessageBubble from './ChatMessageBubble';
import ChatTypingIndicator from './ChatTypingIndicator';
import styles from './ChatAssistant.module.css';

interface ChatMessageListProps {
  messages: ChatUiMessage[];
  isSending: boolean;
  onRetry?: () => void;
  onSelectOption?: (value: string) => void;
}

const ChatMessageList: React.FC<ChatMessageListProps> = ({
  messages,
  isSending,
  onRetry,
  onSelectOption,
}) => {
  const bottomRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages, isSending]);

  return (
    <div
      id="chat-assistant-message-list"
      className={styles.chatMessageList}
      role="log"
      aria-live="polite"
      aria-relevant="additions"
    >
      {messages.length === 0 && (
        <div className={styles.chatEmptyState}>
          <div className={styles.chatEmptyIcon} aria-hidden="true">
            <i className="ri-chat-smile-2-line" />
          </div>
          <p className={styles.chatEmptyTitle}>¿En qué puedo ayudarte?</p>
          <p className="mb-0">
            Consulta clientes, contratos y datos del backoffice. Escribe tu pregunta o elige una opción
            cuando aparezca el menú.
          </p>
        </div>
      )}

      {messages.map((message) => (
        <ChatMessageBubble
          key={message.id}
          message={message}
          isSending={isSending}
          onRetry={message.role === 'error' ? onRetry : undefined}
          onSelectOption={onSelectOption}
        />
      ))}

      {isSending && <ChatTypingIndicator />}

      <div ref={bottomRef} />
    </div>
  );
};

export default ChatMessageList;
