import {
  createContext,
  type FC,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
} from 'react';
import { useParams } from 'react-router-dom';

import { type ConversationMessage } from 'src/pages/dashboard/Conversations/types';

export type ReplayMessageValue = {
  messageToReply: ConversationMessage | null;
};

const ReplayMessageValueContext = createContext<ReplayMessageValue>({
  messageToReply: null,
});

export type ReplayMessageSetter = {
  setReply: (message: ConversationMessage) => void;
  clearReply: () => void;
};

const ReplayMessageSetterContext = createContext<ReplayMessageSetter>({
  setReply: () => null,
  clearReply: () => null,
});

export type ReplyMessagePropsConversation = {};

export const ReplyMessageConversationProvider: FC<
  React.PropsWithChildren<ReplyMessagePropsConversation>
> = props => {
  const { children } = props;
  const { id } = useParams();
  const [messageToReply, setMessageToReply] =
    useState<ConversationMessage | null>(null);

  const setReply = useCallback((message: ConversationMessage) => {
    setMessageToReply(message);
  }, []);

  const clearReply = useCallback(() => {
    setMessageToReply(null);
  }, []);

  useEffect(() => {
    if (id) {
      clearReply();
    }
  }, [id]);

  const memoSetters = useMemo(
    () => ({
      setReply,
      clearReply,
    }),
    [setReply, clearReply],
  );

  return (
    <ReplayMessageValueContext.Provider value={{ messageToReply }}>
      <ReplayMessageSetterContext.Provider value={memoSetters}>
        {children}
      </ReplayMessageSetterContext.Provider>
    </ReplayMessageValueContext.Provider>
  );
};

export const useReplyMessageValue = () => useContext(ReplayMessageValueContext);

export const ReplyMessageConversationConsumer =
  ReplayMessageValueContext.Consumer;

export const useReplayMessageSetter = () =>
  useContext(ReplayMessageSetterContext);

export default { useReplyMessageValue, useReplayMessageSetter };
