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

export default function ProductionListColumnComment({ record, usePortal = false }) {
  const { t } = useTranslation();
  const [note, setNote] = useState(record.comment || "");
  const [open, setOpen] = useState(false);
  const textAreaRef = useRef(null);
  const rafIdRef = useRef(null);

  const [updateAlert] = useMutation(UPDATE_JOB);

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

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

  const handleOpenChange = (flag) => {
    if (rafIdRef.current) {
      cancelAnimationFrame(rafIdRef.current);
      rafIdRef.current = null;
    }
    setOpen(flag);
    if (flag) {
      setNote(record.comment || "");
      rafIdRef.current = requestAnimationFrame(() => {
        rafIdRef.current = null;
        if (textAreaRef.current?.focus) {
          try {
            textAreaRef.current.focus({ preventScroll: true });
          } catch {
            textAreaRef.current.focus();
          }
        }
      });
    }
  };

  const content = (
    <div style={{ width: "30em" }} onClick={(e) => e.stopPropagation()} onPointerDown={(e) => e.stopPropagation()}>
      <Input.TextArea
        id={`job-comment-${record.id}`}
        name="comment"
        rows={5}
        value={note}
        onChange={handleChange}
        ref={textAreaRef}
        allowClear
        style={{ marginBottom: "1em" }}
      />
      <div>
        <Button onClick={handleSaveNote} type="primary">
          {t("general.actions.save")}
        </Button>
      </div>
    </div>
  );

  return (
    <Popover
      onOpenChange={handleOpenChange}
      open={open}
      content={content}
      trigger="click"
      destroyOnHidden
      styles={{ body: { padding: "12px" } }}
      {...(usePortal ? { getPopupContainer: (trigger) => trigger.parentElement || document.body } : {})}
    >
      <div
        style={{
          width: "100%",
          height: "19px",
          cursor: "pointer",
          overflow: "hidden",
          textOverflow: "ellipsis"
        }}
        onClick={(e) => e.stopPropagation()}
      >
        <Icon component={FaRegStickyNote} style={{ marginRight: ".2rem" }} />
        <Tooltip title={record.comment}>{record.comment || " "}</Tooltip>
      </div>
    </Popover>
  );
}
