import React, { ForwardedRef, useEffect, useRef } from 'react';

interface ConversationProps {
  messages: string[];
  onResendClick: () => void;
  onEditClick: () => void;
  onCopyClick: () => void;
}

const ConversationFrontend = React.forwardRef<HTMLDivElement, ConversationProps>(
  ({ messages, onResendClick, onEditClick, onCopyClick }, ref: ForwardedRef<HTMLDivElement>) => {
    const endOfMessagesRef = useRef<HTMLDivElement>(null);

    // Auto-scroll to the bottom of the conversation whenever a new message is added
    useEffect(() => {
      if (endOfMessagesRef.current) {
        endOfMessagesRef.current.scrollIntoView({ behavior: 'smooth' });
      }
    }, [messages]); // Triggers the effect whenever the 'messages' array changes

    return (
      <div className="output">
        <div className="conversation resize" id="conversation" ref={ref}>
          {messages.map((message, index) => {
            const isUserMessage = message.startsWith('User:');
            console.log("output: "+messages)
            return (
              <div
                key={index}
                className={isUserMessage ? 'user-message' : 'ai-message'}
              >
                <p> {message}</p>
              </div>
            );
          })}
          {/* Dummy div to mark the end of the conversation for auto-scrolling */}
          <div ref={endOfMessagesRef} />
          <div className="button-container">
            <button type="button" onClick={onResendClick}>
              <img src="/img/resend.svg" alt="resend" />
            </button>
            <button type="button" onClick={onEditClick}>
              <img src="/img/edit.svg" alt="edit" />
            </button>
            <button type="button" onClick={onCopyClick}>
              <img src="/img/copy.svg" alt="copy" />
            </button>
          </div>
        </div>
      </div>
    );
  }
);

export default ConversationFrontend;
