import { useMutation, useQuery, useSubscription } from "@apollo/client";
import React, { useState } from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { CONVERSATION_SUBSCRIPTION_BY_PK, GET_CONVERSATION_DETAILS } 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";
import axios from "axios";
import { selectBodyshop } from "../../redux/user/user.selectors";

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

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

export function ChatConversationContainer({ bodyshop, selectedConversation }) {
  const {
    loading: convoLoading,
    error: convoError,
    data: convoData
  } = useQuery(GET_CONVERSATION_DETAILS, {
    variables: { conversationId: selectedConversation },
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  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 },
    refetchQueries: ["UNREAD_CONVERSATION_COUNT"],
    update(cache) {
      cache.modify({
        id: cache.identify({
          __typename: "conversations",
          id: selectedConversation
        }),
        fields: {
          messages_aggregate(cached) {
            return { aggregate: { count: 0 } };
          }
        }
      });
    }
  });

  const unreadCount =
    data &&
    data.messages &&
    data.messages.reduce((acc, val) => {
      return !val.read && !val.isoutbound ? acc + 1 : acc;
    }, 0);

  const handleMarkConversationAsRead = async () => {
    if (unreadCount > 0 && !!selectedConversation && !markingAsReadInProgress) {
      setMarkingAsReadInProgress(true);
      await markConversationRead({});
      await axios.post("/sms/markConversationRead", {
        conversationid: selectedConversation,
        imexshopid: bodyshop.imexshopid
      });
      setMarkingAsReadInProgress(false);
    }
  };

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