import Icon from "@ant-design/icons";
import { useMutation } from "@apollo/client";
import { Button, Input, Popover, Tooltip } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { FaRegStickyNote } from "react-icons/fa";
import { UPDATE_JOB } from "../../graphql/jobs.queries";

export default function ProductionListColumnComment({ record }) {
  const { t } = useTranslation();

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

  const [open, setOpen] = useState(false);

  const [updateAlert] = useMutation(UPDATE_JOB);

  const handleSaveNote = (e) => {
    e.stopPropagation();
    setOpen(false);
    updateAlert({
      variables: {
        jobId: record.id,
        job: {
          comment: note
        }
      }
    }).then(() => {
      if (record.refetch) record.refetch();
    });
  };

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

  const handleOpenChange = (flag) => {
    setOpen(flag);
    if (flag) setNote(record.comment || "");
  };

  return (
    <Popover
      onOpenChange={handleOpenChange}
      open={open}
      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",
          display: "inline-block"
        }}
      >
        <Icon component={FaRegStickyNote} style={{ marginRight: ".2rem" }} />
        <Tooltip title={record.comment}>{record.comment || " "}</Tooltip>
      </div>
    </Popover>
  );
}
