import { useMutation } from "@apollo/client";
import { Button } from "antd";
import React, { useContext, useState } from "react";
import { useTranslation } from "react-i18next";
import { TOGGLE_CONVERSATION_ARCHIVE } from "../../graphql/conversations.queries";
import SocketContext from "../../contexts/SocketIO/socketContext.jsx";
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 ChatArchiveButton({ conversation, bodyshop }) {
  const [loading, setLoading] = useState(false);
  const { t } = useTranslation();
  const [updateConversation] = useMutation(TOGGLE_CONVERSATION_ARCHIVE);
  const { socket } = useContext(SocketContext);

  const handleToggleArchive = async () => {
    setLoading(true);

    const updatedConversation = await updateConversation({
      variables: { id: conversation.id, archived: !conversation.archived }
    });

    if (socket) {
      socket.emit("conversation-modified", {
        type: "conversation-archived",
        conversationId: conversation.id,
        bodyshopId: bodyshop.id,
        archived: updatedConversation.data.update_conversations_by_pk.archived
      });
    }

    setLoading(false);
  };

  return (
    <Button onClick={handleToggleArchive} loading={loading} className="archive-button" type="primary">
      {conversation.archived ? t("messaging.labels.unarchive") : t("messaging.labels.archive")}
    </Button>
  );
}

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