import Icon from "@ant-design/icons";
import { useMutation } from "@apollo/client";
import { Button, Input, Popover, Space } from "antd";
import { useCallback, useMemo, 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 }) {
  const { t } = useTranslation();
  const [note, setNote] = useState(record.production_vars?.note || "");
  const [open, setOpen] = useState(false);

  const [updateAlert] = useMutation(UPDATE_JOB);

  const handleSaveNote = useCallback(
    (e) => {
      logImEXEvent("production_add_note");
      e.stopPropagation();
      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) => {
    e.stopPropagation();
    setNote(e.target.value);
  }, []);

  const handleOpenChange = useCallback(
    (flag) => {
      setOpen(flag);
      if (flag) setNote(record.production_vars?.note || "");
    },
    [record]
  );

  const popoverContent = useMemo(
    () => (
      <div style={{ width: "30em" }}>
        <Input.TextArea
          rows={5}
          value={note}
          onChange={handleChange}
          autoFocus
          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>
    ),
    [note, handleSaveNote, handleChange, record, setNoteUpsertContext, t]
  );

  return (
    <Popover onOpenChange={handleOpenChange} open={open} content={popoverContent} trigger={["click"]}>
      <div
        style={{
          width: "100%",
          height: "19px",
          cursor: "pointer",
          overflow: "hidden",
          textOverflow: "ellipsis"
        }}
      >
        <Icon component={FaRegStickyNote} style={{ marginRight: ".2rem" }} />
        {record.production_vars?.note || " "}
      </div>
    </Popover>
  );
}

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