import { Input, Spin } from "antd";
import { LoadingOutlined } from "@ant-design/icons";
import React, { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { sendMessage } from "../../redux/messaging/messaging.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});
const mapDispatchToProps = dispatch => ({
  sendMessage: message => dispatch(sendMessage(message))
});

function ChatSendMessageComponent({ conversation, bodyshop, sendMessage }) {
  const [message, setMessage] = useState("");

  useEffect(() => {
    if (conversation.isSending === false) {
      setMessage("");
    }
  }, [conversation, setMessage]);
  const { t } = useTranslation();

  const handleEnter = () => {
    sendMessage({
      to: conversation.phone_num,
      body: message,
      messagingServiceSid: bodyshop.messagingservicesid,
      conversationid: conversation.id
    });
  };

  return (
    <div style={{ display: "flex " }}>
      <Input.TextArea
        allowClear
        autoFocus
        suffix={<span>a</span>}
        autoSize={{ minRows: 1, maxRows: 4 }}
        value={message}
        disabled={conversation.isSending}
        placeholder={t("messaging.labels.typeamessage")}
        onChange={e => setMessage(e.target.value)}
        onPressEnter={event => {
          event.preventDefault();
          if (!!!event.shiftKey) handleEnter();
        }}
      />
      <Spin
        style={{ display: `${conversation.isSending ? "" : "none"}` }}
        indicator={
          <LoadingOutlined
            style={{
              fontSize: 24
            }}
            spin
          />
        }
      />
    </div>
  );
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ChatSendMessageComponent);
