import React, { useEffect, useRef } from 'react';
import { RxBookmark } from 'react-icons/rx';
import { Link } from 'react-router-dom';
import { useChat } from '../../contexts/Chat/ChatState';
import Message from './Message';


const Messages = () => {
  // #################################
  // HOOKS
  // #################################
  // ### CONNECT CONTEXT
  const { currentChatId, fetchChatHistory, chatHistory } = useChat();

  // ### FETCH HISTORY EVERY TIME THE CHAT ID CHANGES
  useEffect(() => {
    // ### on run exec this code
    const controller = new AbortController();
    // ### fetch chat history based on current chat id
    fetchChatHistory(currentChatId);
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' });

    // ### return will be executed on unmounting this component
    return () => {
      // on unmount abort request
      controller.abort();
    };
  }, [currentChatId]);

  // ### SCROLL TO BOTTOM
  const bottomRef = useRef();
  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [chatHistory]);

  // #################################
  // FUNCTIONS
  // #################################

  // #################################
  // OUTPUT
  // #################################
  return (
    <div className="row-start-2 overflow-auto">
      {currentChatId && <Link to={`/onboarding/${currentChatId}`} className='text-UhhBlue' target='_blank' rel='noopener noreferrer'><RxBookmark /></Link>}
      {chatHistory.map((chat, index) => (
        <Message
          key={index}
          chat={chat}
        />
      ))
      }

      {!chatHistory.length && <div className="text-center text-gray-500">No messages yet</div>}

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

export default Messages;