import { useMutation } from "@apollo/client/react";
import { Tag } from "antd";
import { Link } from "react-router-dom";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { REMOVE_CONVERSATION_TAG } from "../../graphql/job-conversations.queries";
import OwnerNameDisplay from "../owner-name-display/owner-name-display.component";
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 ChatConversationTitleTags({ jobConversations, bodyshop }) {
  const [removeJobConversation] = useMutation(REMOVE_CONVERSATION_TAG);
  const { socket } = useSocket();

  const handleRemoveTag = async (jobId) => {
    const convId = jobConversations[0].conversationid;
    if (convId) {
      await removeJobConversation({
        variables: {
          conversationId: convId,
          jobId: jobId
        },
        update(cache) {
          cache.modify({
            id: cache.identify({ id: convId, __typename: "conversations" }),
            fields: {
              job_conversations(ex) {
                return ex.filter((e) => e.jobid !== jobId);
              }
            }
          });
        }
      });

      if (socket) {
        // Emit the `conversation-modified` event
        socket.emit("conversation-modified", {
          bodyshopId: bodyshop.id,
          conversationId: convId,
          type: "tag-removed",
          jobId: jobId
        });
      }

      logImEXEvent("messaging_remove_job_tag", {
        conversationId: convId,
        jobId: jobId
      });
    }
  };

  return (
    <div>
      {jobConversations.map((item) => (
        <Tag
          key={item.job.id}
          closable
          color="blue"
          style={{ cursor: "pointer" }}
          onClose={() => handleRemoveTag(item.job.id)}
        >
          <Link to={`/manage/jobs/${item.job.id}`}>
            {`${item.job.ro_number || "?"} | `}
            <OwnerNameDisplay ownerObject={item.job} />
          </Link>
        </Tag>
      ))}
    </div>
  );
}

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