import { useMutation } from "@apollo/client";
import { Tag } from "antd";
import React from "react";
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";

export default function ChatConversationTitleTags({ jobConversations }) {
  const [removeJobConversation] = useMutation(REMOVE_CONVERSATION_TAG);

  const handleRemoveTag = (jobId) => {
    const convId = jobConversations[0].conversationid;
    if (!!convId) {
      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);
              },
            },
          });
        },
      });
      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>
  );
}
