import React, { useCallback, useEffect, useState } from "react";
import PropTypes from "prop-types";
import {
  DirectChatNewMessageContainer,
  NewMessageField,
  SendButton,
} from "./DirectChatNewMessage.styled";
import { useTranslation } from "react-i18next";
import selectedTheme from "../../../themes";
import { useDispatch } from "react-redux";
import {
  fetchChats,
  sendMessage,
  startNewChat,
} from "../../../store/actions/chat/chatActions";
import { useHistory, useLocation } from "react-router-dom";

const DirectChatNewMessage = (props) => {
  const [typedValue, setTypedValue] = useState("");
  const [isFocused, setIsFocused] = useState(false);
  const dispatch = useDispatch();
  const { t } = useTranslation();
  const location = useLocation();
  const history = useHistory();
  const handleApiResponseSuccess = () => {
    props.refreshChat();
  };
  const handleSend = useCallback(() => {
    console.log(typedValue);
    if (location.state?.offerId) {
      initiateNewChat(typedValue);
    } else {
      dispatch(
        sendMessage({
          message: typedValue,
          chatId: props.chatId,
          handleApiResponseSuccess,
        })
      );
    }
    setTypedValue("");
  }, [typedValue]);
  const handleMessageSendSuccess = (newChatId) => {
    history.replace(`${newChatId}`);
    dispatch(fetchChats());
  };

  useEffect(() => {
    const listener = (event) => {
      if (event.keyCode === 13) handleSend();
    };
    if (isFocused) window.addEventListener("keypress", listener);
    return () => window.removeEventListener("keypress", listener);
  }, [typedValue]);

  const initiateNewChat = (typedValue) => {
    const offerId = location.state.offerId;
    dispatch(
      startNewChat({ offerId, message: typedValue, handleMessageSendSuccess })
    );
  };
  return (
    <DirectChatNewMessageContainer>
      <NewMessageField
        placeholder={t("messages.sendPlaceholder")}
        fullWidth
        onFocus={() => setIsFocused(true)}
        onBlur={() => setIsFocused(false)}
        italicPlaceholder
        value={typedValue}
        onChange={(typed) => setTypedValue(typed.target.value)}
      />
      <SendButton
        onClick={handleSend}
        buttoncolor={selectedTheme.primaryPurple}
        variant="contained"
      >
        {t("messages.send")}
      </SendButton>
    </DirectChatNewMessageContainer>
  );
};

DirectChatNewMessage.propTypes = {
  children: PropTypes.node,
  chatId: PropTypes.any,
  refreshChat: PropTypes.func,
};

export default DirectChatNewMessage;
