import { LoadingOutlined, SendOutlined } from "@ant-design/icons";
import { Input, Spin } from "antd";
import React, { useContext, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { setMessage } from "../../redux/messaging/messaging.actions";
import { selectIsSending, selectMessage } from "../../redux/messaging/messaging.selectors";
import { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors";
import ChatMediaSelector from "../chat-media-selector/chat-media-selector.component";
import ChatPresetsComponent from "../chat-presets/chat-presets.component";
import SocketContext from "../../contexts/SocketIO/socketContext.jsx";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  isSending: selectIsSending,
  message: selectMessage,
  user: selectCurrentUser
});

const mapDispatchToProps = (dispatch) => ({
  setMessage: (message) => dispatch(setMessage(message))
});

function ChatSendMessageComponent({ conversation, bodyshop, isSending, message, setMessage, user }) {
  const { socket } = useContext(SocketContext); // Access WebSocket instance
  const inputArea = useRef(null);
  const [selectedMedia, setSelectedMedia] = useState([]);
  const { t } = useTranslation();

  useEffect(() => {
    inputArea.current.focus();
  }, [isSending, setMessage]);

  const handleEnter = () => {
    const selectedImages = selectedMedia.filter((i) => i.isSelected);
    if ((message === "" || !message) && selectedImages.length === 0) return;

    logImEXEvent("messaging_send_message");

    if (selectedImages.length < 11) {
      const messageData = {
        user,
        to: conversation.phone_num,
        body: message || "",
        messagingServiceSid: bodyshop.messagingservicesid,
        conversationid: conversation.id,
        selectedMedia: selectedImages,
        imexshopid: bodyshop.imexshopid
      };

      // Emit the send-message event via WebSocket
      socket.emit("send-message", messageData);

      setSelectedMedia(
        selectedMedia.map((i) => {
          return { ...i, isSelected: false };
        })
      );

      // Optionally clear the input message
      setMessage("");
    }
  };

  return (
    <div className="imex-flex-row" style={{ width: "100%" }}>
      <ChatPresetsComponent className="imex-flex-row__margin" />
      <ChatMediaSelector
        conversation={conversation}
        selectedMedia={selectedMedia}
        setSelectedMedia={setSelectedMedia}
      />
      <span style={{ flex: 1 }}>
        <Input.TextArea
          className="imex-flex-row__margin imex-flex-row__grow"
          allowClear
          autoFocus
          ref={inputArea}
          autoSize={{ minRows: 1, maxRows: 4 }}
          value={message}
          disabled={isSending}
          placeholder={t("messaging.labels.typeamessage")}
          onChange={(e) => setMessage(e.target.value)}
          onPressEnter={(event) => {
            event.preventDefault();
            if (!event.shiftKey) handleEnter();
          }}
        />
      </span>
      <SendOutlined className="imex-flex-row__margin" onClick={handleEnter} />
      <Spin
        style={{ display: `${isSending ? "" : "none"}` }}
        indicator={
          <LoadingOutlined
            style={{
              fontSize: 24
            }}
            spin
          />
        }
      />
    </div>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(ChatSendMessageComponent);
