import { useMutation } from "@apollo/client/react";
import { Button } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { TOGGLE_CONVERSATION_ARCHIVE } from "../../graphql/conversations.queries";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors.js";
import { connect } from "react-redux";
import { useSocket } from "../../contexts/SocketIO/useSocket.js";

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 } = useSocket();

  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);
