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

type Message = {
  role: string
  content: string
}

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

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

    useEffect(() => {
      if (ref && typeof ref !== 'function') {
        const element = ref as React.RefObject<HTMLDivElement>;
        if (element.current) {
          element.current.scrollTop = element.current.scrollHeight;
        }
      }
    }, [messages, ref]);

    return (
      <div className="output" ref={ref}>
        <div className="conversation resize" id="conversation">
          {messages.map((message, index) => {
            if (index >= 1){

              return (
                <div
                  key={index}
                  className={message.role === "user" ? 'user-message' : 'ai-message'}
                  >
                  <p> {message.content}</p>
                </div>
              );
            }
          })}

          <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>
            <p id="copiedText" style={{opacity:isClicked?"1":"0", transition:"all 0.3s ease-in-out"}}>Copied!</p>
          </div>
        </div>
      </div>
    );
  }
);

export default ConversationFrontend;
