import Icon from "@ant-design/icons";
import { useMutation } from "@apollo/client";
import { Button, Input, Popover } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { FaRegStickyNote } from "react-icons/fa";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { UPDATE_JOB } from "../../graphql/jobs.queries";
export default function ProductionListColumnProductionNote({ record }) {
  const { t } = useTranslation();

  const [note, setNote] = useState(
    (record.production_vars && record.production_vars.note) || ""
  );

  const [visible, setVisible] = useState(false);

  const [updateAlert] = useMutation(UPDATE_JOB);

  const handleSaveNote = (e) => {
    logImEXEvent("production_add_note");
    e.stopPropagation();
    setVisible(false);
    updateAlert({
      variables: {
        jobId: record.id,
        job: {
          production_vars: {
            ...record.production_vars,
            note: note,
          },
        },
      },
    }).then(() => {
      if (record.refetch) record.refetch();
    });
  };

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

  const handleVisibleChange = (flag) => {
    setVisible(flag);
    if (flag)
      setNote((record.production_vars && record.production_vars.note) || "");
  };

  return (
    <Popover
      onVisibleChange={handleVisibleChange}
      visible={visible}
      content={
        <div style={{ width: "30em" }}>
          <Input.TextArea
            rows={5}
            value={note}
            onChange={handleChange}
            // onPressEnter={handleSaveNote}
            autoFocus
            allowClear
          />
          <div>
            <Button onClick={handleSaveNote}>
              {t("general.actions.save")}
            </Button>
          </div>
        </div>
      }
      trigger={["click"]}
    >
      <div
        style={{
          width: "100%",
          height: "19px",
          cursor: "pointer",
          overflow: "hidden",
          textOverflow: "ellipsis",
        }}
      >
        <Icon component={FaRegStickyNote} style={{ marginRight: ".2rem" }} />
        {(record.production_vars && record.production_vars.note) || " "}
      </div>
    </Popover>
  );
}
