import { FieldTimeOutlined } from "@ant-design/icons";
import { useMutation } from "@apollo/client/react";
import { Input } from "antd";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { UPDATE_JOB_LINE } from "../../graphql/jobs-lines.queries";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

export default function JobLineNotePopup({ jobline, disabled }) {
  const [editing, setEditing] = useState(false);
  const [loading, setLoading] = useState(false);
  const [note, setNote] = useState(jobline.note);
  const [updateJob] = useMutation(UPDATE_JOB_LINE);
  const { t } = useTranslation();
  const notification = useNotification();

  useEffect(() => {
    if (editing) setNote(jobline.notes);
  }, [editing, jobline.notes]);

  const handleChange = (e) => {
    e.stopPropagation();
    setNote(e.currentTarget.value);
  };

  const handleSave = async (e) => {
    e.stopPropagation();
    setLoading(true);
    const result = await updateJob({
      variables: { lineId: jobline.id, line: { notes: note || "" } }
    });

    if (!result.errors) {
      notification.success({ title: t("joblines.successes.saved") });
    } else {
      notification.error({
        title: t("joblines.errors.saving", {
          error: JSON.stringify(result.errors)
        })
      });
    }
    setLoading(false);
    setEditing(false);
  };

  if (editing)
    return (
      <div>
        <Input.TextArea
          autoSize
          autoFocus
          suffix={loading ? <LoadingSpinner /> : null}
          value={note}
          onChange={handleChange}
          onPressEnter={handleSave}
          onBlur={handleSave}
        />
      </div>
    );
  return (
    <div>
      <div
        style={{
          width: "100%",
          ...(jobline.ioucreated ? {} : { minHeight: "2rem" }),
          cursor: "pointer"
        }}
        onClick={() => !disabled && setEditing(true)}
      >
        {jobline.ioucreated && (
          <div>
            <FieldTimeOutlined style={{ margin: 0, padding: 0 }} />
            {t("joblines.labels.ioucreated")}
          </div>
        )}
        {jobline.notes || null}
      </div>
    </div>
  );
}
