import { useMutation, useSubscription } from "@apollo/client";
import React, { useState } from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { CONVERSATION_SUBSCRIPTION_BY_PK } from "../../graphql/conversations.queries";
import { MARK_MESSAGES_AS_READ_BY_CONVERSATION } from "../../graphql/messages.queries";
import { selectSelectedConversation } from "../../redux/messaging/messaging.selectors";
import ChatConversationComponent from "./chat-conversation.component";
const mapStateToProps = createStructuredSelector({
  selectedConversation: selectSelectedConversation,
});

export default connect(mapStateToProps, null)(ChatConversationContainer);

export function ChatConversationContainer({ selectedConversation }) {
  const { loading, error, data } = useSubscription(
    CONVERSATION_SUBSCRIPTION_BY_PK,
    {
      variables: { conversationId: selectedConversation },
    }
  );

  const [markingAsReadInProgress, setMarkingAsReadInProgress] = useState(false);

  const [markConversationRead] = useMutation(
    MARK_MESSAGES_AS_READ_BY_CONVERSATION,
    {
      variables: { conversationId: selectedConversation },
    }
  );

  const unreadCount =
    (data &&
      data.conversations_by_pk &&
      data.conversations_by_pk &&
      data.conversations_by_pk.messages_aggregate &&
      data.conversations_by_pk.messages_aggregate.aggregate &&
      data.conversations_by_pk.messages_aggregate.aggregate.count) ||
    0;

  const handleMarkConversationAsRead = async () => {
    if (unreadCount > 0 && !!selectedConversation && !markingAsReadInProgress) {
      setMarkingAsReadInProgress(true);
      await markConversationRead();
      setMarkingAsReadInProgress(false);
    }
  };

  return (
    <ChatConversationComponent
      subState={[loading, error]}
      conversation={data ? data.conversations_by_pk : {}}
      handleMarkConversationAsRead={handleMarkConversationAsRead}
    />
  );
}
