import React from 'react';
import { useChat } from '../../providers/chat-provider';
import { useSound } from '../../providers/sound-provider';
import { Message } from '../../types';
import '../../styles/chat.css';

interface MessageListProps {
  messages: Message[];
}

export function MessageList({ messages }: MessageListProps) {
  const scrollRef = React.useRef(null);
  const { user } = useChat();
  const { playSound } = useSound();
  const prevMessagesLength = React.useRef(messages.length);

  React.useEffect(() => {
    if (messages.length > prevMessagesLength.current) {
      const lastMessage = messages[messages.length - 1];
      if (lastMessage.from.id !== user.id) {
        playSound('receive');
      }
      scrollRef.current?.scrollIntoView({ behavior: 'smooth' });
    }
    prevMessagesLength.current = messages.length;
  }, [messages]);

  return (
    <div className="message-list" ref={scrollRef}>
      {messages.map((message, index) => (
        <div
          key={`${message.id}-${index}`}
          className={`message-container ${message.from.id === user.id ? 'user-message' : 'bot-message'}`}
        >
          <p className="message-text">{message.text}</p>
          <span className="message-time">{new Date(message.timestamp).toLocaleTimeString()}</span>
        </div>
      ))}
    </div>
  );
}
