import "../DocumentCard.css";
import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useMemo, useRef, useEffect, useCallback } from "react";
import Button from "./Button.js";
import Icon from "./Icon.js";
import Input from "./Input.js";
import Markdown from "./internal/Markdown.js";
import Spinner from "./Spinner.js";
import { useTheme } from "./Theme/UI.js";
import "./Theme/themeUtils.js";
import "./Theme/themes.js";
import { ErrorType } from "./utils/error.js";
import Column from "./Column.js";
import { Row } from "./Row.js";
import Surface from "./Surface.js";
const base = "DocumentCard_base_df39a";
const css = {
  base
};
const DocumentCard = ({
  disabled = false,
  disableTitle = false,
  doc,
  extra,
  onChange,
  onError,
  onSaveDocument,
  onPageUnloadHook,
  documentChangeSignal
}) => {
  const {
    themeSettings: { className: themeClass }
  } = useTheme();
  const classes = [css.base, themeClass];
  const [isEditing, setIsEditing] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [editedDocs, setEditedDocs] = useState((doc == null ? void 0 : doc.contents) || "");
  const [editedTitle, setEditedTitle] = useState((doc == null ? void 0 : doc.name) || "");
  const [docs, title] = useMemo(() => [(doc == null ? void 0 : doc.contents) || "", (doc == null ? void 0 : doc.name) || ""], [doc]);
  const blocker = () => {
    if (isEditing && docs !== editedDocs) {
      const answer = window.confirm(
        "You have unsaved documents, are you sure you want to leave? Unsaved documents will be lost."
      );
      return !answer;
    }
    return false;
  };
  onPageUnloadHook == null ? void 0 : onPageUnloadHook(blocker);
  const existingDocs = useRef(docs);
  const existingTitle = useRef(title);
  useEffect(() => {
    existingDocs.current = docs;
  }, [docs]);
  useEffect(() => {
    existingTitle.current = title;
    setEditedTitle(title);
  }, [title]);
  useEffect(() => {
    setIsEditing(false);
    setIsLoading(false);
    setEditedDocs(existingDocs.current);
    setEditedTitle(existingTitle.current);
  }, [documentChangeSignal]);
  const editDocs = useCallback(() => {
    if (disabled)
      return;
    setIsEditing(true);
  }, [disabled]);
  const cancelEdit = useCallback(() => {
    setIsEditing(false);
    setEditedDocs(docs);
    onChange == null ? void 0 : onChange(docs);
    setEditedTitle(title);
  }, [docs, title, onChange]);
  const onSave = useCallback(
    async (editDocs2) => {
      await onSaveDocument({ contents: editDocs2, name: editedTitle });
    },
    [onSaveDocument, editedTitle]
  );
  const onSaveTitle = useCallback(
    async (editTitle) => {
      await onSaveDocument({ contents: editedDocs, name: editTitle });
    },
    [onSaveDocument, editedDocs]
  );
  const saveDocs = useCallback(async () => {
    try {
      setIsLoading(true);
      await (onSave == null ? void 0 : onSave(editedDocs.trim()));
      setIsEditing(false);
    } catch (e) {
      onError(e, {
        publicSubject: "Unable to update documents.",
        silent: true,
        type: ErrorType.Api
      });
    }
    setIsLoading(false);
  }, [editedDocs, onSave, onError]);
  const handleEditedDocs = useCallback(
    (newDocs) => {
      setEditedDocs(newDocs);
      onChange == null ? void 0 : onChange(newDocs);
    },
    [onChange]
  );
  const handleDocsClick = useCallback(
    (e) => {
      if (e.detail > 1 || docs === "")
        editDocs();
    },
    [editDocs, docs]
  );
  useEffect(() => {
    setEditedDocs(docs);
    setIsEditing(false);
  }, [docs]);
  return /* @__PURE__ */ jsx(Surface, { children: /* @__PURE__ */ jsxs("div", { className: classes.join(" "), children: [
    /* @__PURE__ */ jsxs(Row, { children: [
      /* @__PURE__ */ jsx(Column, { children: /* @__PURE__ */ jsx(
        Input,
        {
          defaultValue: title,
          disabled: disableTitle || disabled,
          value: editedTitle,
          onBlur: (e) => {
            const newValue = e.currentTarget.value;
            onSaveTitle == null ? void 0 : onSaveTitle(newValue);
          },
          onChange: (e) => {
            const newValue = e.currentTarget.value;
            setEditedTitle(newValue);
          },
          onPressEnter: (e) => {
            e.currentTarget.blur();
          }
        }
      ) }),
      /* @__PURE__ */ jsx(Column, { align: "right", children: isEditing ? /* @__PURE__ */ jsxs(Row, { children: [
        /* @__PURE__ */ jsx(Button, { size: "small", onClick: cancelEdit, children: "Cancel" }),
        /* @__PURE__ */ jsx(Button, { size: "small", type: "primary", onClick: saveDocs, children: "Save" })
      ] }) : disabled || /* @__PURE__ */ jsxs(Row, { children: [
        /* @__PURE__ */ jsx(
          Button,
          {
            icon: /* @__PURE__ */ jsx(Icon, { name: "pencil", showTooltip: true, size: "small", title: "Edit" }),
            type: "text",
            onClick: editDocs
          }
        ),
        extra
      ] }) })
    ] }),
    /* @__PURE__ */ jsx(Spinner, { spinning: isLoading, children: /* @__PURE__ */ jsx(
      Markdown,
      {
        disabled,
        editing: isEditing,
        markdown: isEditing ? editedDocs : docs,
        onChange: handleEditedDocs,
        onClick: handleDocsClick
      }
    ) })
  ] }) });
};
export {
  DocumentCard as default
};
