import { useSubscription } from "@apollo/client";
import React from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { CONVERSATION_LIST_SUBSCRIPTION } from "../../graphql/conversations.queries";
import { selectChatVisible } from "../../redux/messaging/messaging.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import AlertComponent from "../alert/alert.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import ChatAffixComponent from "./chat-affix.component";
import "./chat-affix.styles.scss";

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

export function ChatAffixContainer({ bodyshop, chatVisible }) {
  const { loading, error, data } = useSubscription(
    CONVERSATION_LIST_SUBSCRIPTION,
    {
      skip: !bodyshop || (bodyshop && !bodyshop.messagingservicesid),
    }
  );

  if (loading) return <LoadingSpinner />;
  if (error) return <AlertComponent message={error.message} type="error" />;

  if (!bodyshop || !bodyshop.messagingservicesid) return <></>;

  return (
    <div className={`chat-affix ${chatVisible ? "chat-affix-open" : ""}`}>
      {bodyshop && bodyshop.messagingservicesid ? (
        <ChatAffixComponent
          conversationList={(data && data.conversations) || []}
          unreadCount={
            (data &&
              data.conversations.reduce((acc, val) => {
                return (acc = acc + val.messages_aggregate.aggregate.count);
              }, 0)) ||
            0
          }
        />
      ) : null}
    </div>
  );
}
export default connect(mapStateToProps, null)(ChatAffixContainer);
