import AlertComponent from "../alert/alert.component";
import ChatConversationTitle from "../chat-conversation-title/chat-conversation-title.component";
import ChatMessageListComponent from "../chat-messages-list/chat-message-list.component";
import ChatSendMessage from "../chat-send-message/chat-send-message.component";
import LoadingSkeleton from "../loading-skeleton/loading-skeleton.component.jsx";
import "./chat-conversation.styles.scss";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors.js";
import { connect } from "react-redux";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});

const mapDispatchToProps = () => ({});

export function ChatConversationComponent({
  subState,
  conversation,
  messages,
  handleMarkConversationAsRead,
  handleMarkLastMessageAsUnread,
  markingAsUnreadInProgress,
  canMarkUnread
}) {
  const [loading, error] = subState;

  if (conversation?.archived) return null;
  if (loading) return <LoadingSkeleton />;
  if (error) return <AlertComponent title={error.message} type="error" />;

  return (
    <div
      className="chat-conversation"
      onMouseDown={handleMarkConversationAsRead}
      onKeyDown={handleMarkConversationAsRead}
    >
      <ChatConversationTitle
        conversation={conversation}
        onMarkUnread={handleMarkLastMessageAsUnread}
        markUnreadDisabled={!canMarkUnread}
        markUnreadLoading={markingAsUnreadInProgress}
      />
      <ChatMessageListComponent messages={messages} />
      <ChatSendMessage conversation={conversation} />
    </div>
  );
}

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