import { FC, createContext, useState, useContext } from 'react';

import { Message } from 'src/types/chats';

export type ReplyMessageContextValue = {
  messageToReply: Message;
  setReply: (message: Message) => void;
  clearReply: () => void;
  isReplying: boolean;
};

const ReplyMessageContext = createContext<ReplyMessageContextValue>({
  messageToReply: null,
  setReply: () => null,
  clearReply: () => null,
  isReplying: false,
});

export type ReplyMessageProps = { inViewMessagesEnd: boolean };

export const ReplyMessageProvider: FC<
  React.PropsWithChildren<ReplyMessageProps>
> = props => {
  const { children, inViewMessagesEnd } = props;

  const [messageToReply, setMessageToReply] = useState<Message | null>(null);
  const [isReplying, setIsReplying] = useState<boolean>(false);

  const setReply = (message: Message) => {
    setMessageToReply(message);
    setIsReplying(true);
    if (inViewMessagesEnd) {
      setTimeout(() => {
        const chatBox = document.getElementById('chat-window');
        chatBox.scrollTo({
          top: chatBox.scrollHeight,
          left: 0,
          behavior: 'smooth',
        });
      }, 10);
    }
  };

  const clearReply = () => {
    setMessageToReply(null);
    setIsReplying(false);
  };

  return (
    <ReplyMessageContext.Provider
      value={{
        messageToReply,
        setReply,
        clearReply,
        isReplying,
      }}
    >
      {children}
    </ReplyMessageContext.Provider>
  );
};

export const useReplyMessage = () => useContext(ReplyMessageContext);

export const ReplyMessageConsumer = ReplyMessageContext.Consumer;

export default ReplyMessageContext;
