import { PlusOutlined } from "@ant-design/icons";
import { useMutation } from "@apollo/client";
import { Input, notification, Spin, Tag, Tooltip } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { UPDATE_CONVERSATION_LABEL } from "../../graphql/conversations.queries";

export default function ChatLabel({ conversation }) {
  const [loading, setLoading] = useState(false);
  const [editing, setEditing] = useState(false);
  const [value, setValue] = useState(conversation.label);

  const { t } = useTranslation();
  const [updateLabel] = useMutation(UPDATE_CONVERSATION_LABEL);

  const handleSave = async () => {
    setLoading(true);
    try {
      const response = await updateLabel({
        variables: { id: conversation.id, label: value }
      });
      if (response.errors) {
        notification["error"]({
          message: t("messages.errors.updatinglabel", {
            error: JSON.stringify(response.errors)
          })
        });
      } else {
        setEditing(false);
      }
    } catch (error) {
      notification["error"]({
        message: t("messages.errors.updatinglabel", {
          error: JSON.stringify(error)
        })
      });
    } finally {
      setLoading(false);
    }
  };
  if (editing) {
    return (
      <div>
        <Input autoFocus value={value} onChange={(e) => setValue(e.target.value)} onBlur={handleSave} allowClear />
        {loading && <Spin size="small" />}
      </div>
    );
  } else {
    return conversation.label && conversation.label.trim() !== "" ? (
      <Tag style={{ cursor: "pointer" }} onClick={() => setEditing(true)}>
        {conversation.label}
      </Tag>
    ) : (
      <Tooltip title={t("messaging.labels.addlabel")}>
        <PlusOutlined style={{ cursor: "pointer" }} onClick={() => setEditing(true)} />
      </Tooltip>
    );
  }
}
