import { PlusOutlined } from "@ant-design/icons";
import { useLazyQuery, useMutation } from "@apollo/client/react";
import { Tag } from "antd";
import _ from "lodash";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { INSERT_CONVERSATION_TAG } from "../../graphql/job-conversations.queries";
import { SEARCH_FOR_JOBS } from "../../graphql/jobs.queries";
import ChatTagRo from "./chat-tag-ro.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 ChatTagRoContainer({ conversation, bodyshop }) {
  const { t } = useTranslation();
  const [open, setOpen] = useState(false);
  const { socket } = useSocket();

  const [loadRo, { loading, data }] = useLazyQuery(SEARCH_FOR_JOBS);

  const executeSearch = (v) => {
    logImEXEvent("messaging_search_job_tag", { searchTerm: v });
    loadRo({ variables: v }).catch((e) => console.error("Error in ChatTagRoContainer executeSearch:", e));
  };

  const debouncedExecuteSearch = _.debounce(executeSearch, 500);

  const handleSearch = (value) => {
    debouncedExecuteSearch({ search: value });
  };

  const [insertTag] = useMutation(INSERT_CONVERSATION_TAG, {
    variables: { conversationId: conversation.id }
  });

  const handleInsertTag = async (value, option) => {
    logImEXEvent("messaging_add_job_tag");

    await insertTag({
      variables: { jobId: option.key }
    });

    if (socket) {
      // Find the job details from the search data
      const selectedJob = data?.search_jobs.find((job) => job.id === option.key);
      if (!selectedJob) return;
      socket.emit("conversation-modified", {
        conversationId: conversation.id,
        bodyshopId: bodyshop.id,
        type: "tag-added",
        selectedJob,
        job_conversations: [
          {
            __typename: "job_conversations",
            jobid: selectedJob.id,
            conversationid: conversation.id,
            job: {
              __typename: "jobs",
              id: selectedJob.id,
              ro_number: selectedJob.ro_number,
              ownr_co_nm: selectedJob.ownr_co_nm,
              ownr_fn: selectedJob.ownr_fn,
              ownr_ln: selectedJob.ownr_ln
            }
          }
        ]
      });
    }

    setOpen(false);
  };

  const existingJobTags =
    conversation && conversation.job_conversations && conversation.job_conversations.map((i) => i.jobid);

  const roOptions = data ? data.search_jobs.filter((job) => !existingJobTags.includes(job.id)) : [];

  return (
    <div>
      {open ? (
        <ChatTagRo
          loading={loading}
          roOptions={roOptions}
          handleSearch={handleSearch}
          handleInsertTag={handleInsertTag}
          setOpen={setOpen}
          style={{ cursor: "pointer" }}
        />
      ) : (
        <Tag style={{ cursor: "pointer" }} onClick={() => setOpen(true)}>
          <PlusOutlined />
          {t("messaging.actions.link")}
        </Tag>
      )}
    </div>
  );
}

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