import { PlusOutlined } from "@ant-design/icons";
import { useLazyQuery, useMutation } from "@apollo/client";
import { Tag } from "antd";
import _ from "lodash";
import React, { 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";

export default function ChatTagRoContainer({ conversation }) {
  const { t } = useTranslation();
  const [open, setOpen] = useState(false);

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

  const executeSearch = (v) => {
    logImEXEvent("messaging_search_job_tag", { searchTerm: v });
    loadRo(v);
  };

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

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

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

  const handleInsertTag = (value, option) => {
    logImEXEvent("messaging_add_job_tag");
    insertTag({ variables: { jobId: option.key } });
    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}
        />
      ) : (
        <Tag onClick={() => setOpen(true)}>
          <PlusOutlined />
          {t("messaging.actions.link")}
        </Tag>
      )}
    </div>
  );
}
