import Icon from "@ant-design/icons";
import { useMutation } from "@apollo/client/react";
import { Button, Input, Popover, Space } from "antd";
import { useCallback, useRef, 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";
import { setModalContext } from "../../redux/modals/modals.actions";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";

const mapStateToProps = createStructuredSelector({});

const mapDispatchToProps = (dispatch) => ({
  setNoteUpsertContext: (context) => dispatch(setModalContext({ context: context, modal: "noteUpsert" }))
});

function ProductionListColumnProductionNote({ record, setNoteUpsertContext, usePortal = false }) {
  const { t } = useTranslation();
  const [note, setNote] = useState(record.production_vars?.note || "");
  const [open, setOpen] = useState(false);
  const textAreaRef = useRef(null);
  const rafIdRef = useRef(null);

  const [updateAlert] = useMutation(UPDATE_JOB);

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

  const handleChange = useCallback((e) => {
    setNote(e.target.value);
  }, []);

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

  const content = (
    <div style={{ width: "30em" }} onClick={(e) => e.stopPropagation()} onPointerDown={(e) => e.stopPropagation()}>
      <Input.TextArea
        id={`job-production-note-${record.id}`}
        name="production_note"
        rows={5}
        value={note}
        onChange={handleChange}
        ref={textAreaRef}
        allowClear
        style={{ marginBottom: "1em" }}
      />
      <Space>
        <Button onClick={handleSaveNote} type="primary">
          {t("general.actions.save")}
        </Button>
        <Button
          onClick={() => {
            setOpen(false);
            setNoteUpsertContext({
              context: {
                jobId: record.id,
                text: note
              }
            });
          }}
        >
          {t("notes.actions.savetojobnotes")}
        </Button>
      </Space>
    </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" }} />
        {record.production_vars?.note || " "}
      </div>
    </Popover>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(ProductionListColumnProductionNote);
