import "../DocumentCards.css";
import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import { noop } from "lodash";
import { useState, useCallback, useMemo, useEffect } from "react";
import Button from "./Button.js";
import Column from "./Column.js";
import DocumentCard from "./DocumentCard.js";
import Dropdown from "./Dropdown.js";
import Icon from "./Icon.js";
import Message from "./Message.js";
import { Row } from "./Row.js";
import Select, { Option } from "./Select.js";
import Surface from "./Surface.js";
import { useTheme } from "./Theme/UI.js";
import "./Theme/themeUtils.js";
import "./Theme/themes.js";
import useConfirm from "./useConfirm.js";
import usePrevious from "./utils/usePrevious.js";
const breakpointMobile = "768px";
const base = "DocumentCards_base_28b80";
const pageSelectRow = "DocumentCards_pageSelectRow_28b80";
const listContainer = "DocumentCards_listContainer_28b80";
const listItem = "DocumentCards_listItem_28b80";
const action = "DocumentCards_action_28b80";
const docsContainer = "DocumentCards_docsContainer_28b80";
const css = {
  breakpointMobile,
  base,
  pageSelectRow,
  listContainer,
  listItem,
  action,
  docsContainer
};
const DocCards = ({
  docs,
  onNewPage,
  onSave,
  onDelete,
  onError,
  onPageUnloadHook,
  disabled = false
}) => {
  var _a;
  const {
    themeSettings: { className: themeClass }
  } = useTheme();
  const [currentPage, setCurrentPage] = useState(0);
  const [deleteTarget, setDeleteTarget] = useState(0);
  const [editedContents, setEditedContents] = useState(((_a = docs == null ? void 0 : docs[currentPage]) == null ? void 0 : _a.contents) ?? "");
  const confirm = useConfirm();
  const [docChangeSignal, setDocChangeSignal] = useState(1);
  const fireDocChangeSignal = useCallback(
    () => setDocChangeSignal((prev) => prev === 100 ? 1 : prev + 1),
    [setDocChangeSignal]
  );
  const prevDocCount = usePrevious(docs.length, void 0);
  const DROPDOWN_MENU = useMemo(
    () => [{ danger: true, disabled: !onDelete, key: "delete", label: "Delete..." }],
    [onDelete]
  );
  const handleSwitchPage = useCallback(
    (pageNumber) => {
      var _a2, _b;
      if (pageNumber === currentPage)
        return;
      if (editedContents !== ((_a2 = docs == null ? void 0 : docs[currentPage]) == null ? void 0 : _a2.contents)) {
        confirm({
          content: /* @__PURE__ */ jsx("p", { children: "You have unsaved documents, are you sure you want to switch pages? Unsaved documents will be lost." }),
          onConfirm: () => {
            setCurrentPage(pageNumber);
            fireDocChangeSignal();
          },
          onError: noop,
          title: "Unsaved content"
        });
      } else {
        setCurrentPage(pageNumber);
        setEditedContents(((_b = docs == null ? void 0 : docs[currentPage]) == null ? void 0 : _b.contents) ?? "");
        fireDocChangeSignal();
      }
    },
    [currentPage, editedContents, confirm, docs, fireDocChangeSignal]
  );
  useEffect(() => {
    if (prevDocCount == null) {
      if (docs.length) {
        handleSwitchPage(0);
        fireDocChangeSignal();
      }
    } else if (docs.length > prevDocCount) {
      handleSwitchPage(docs.length - 1);
    } else if (docs.length < prevDocCount) {
      setCurrentPage(
        (prevPageNumber) => prevPageNumber > deleteTarget ? prevPageNumber - 1 : prevPageNumber
      );
    }
  }, [prevDocCount, docs.length, deleteTarget, handleSwitchPage, fireDocChangeSignal]);
  const handleNewPage = useCallback(() => {
    const currentPages = docs.length;
    onNewPage();
    handleSwitchPage(currentPages);
  }, [docs.length, onNewPage, handleSwitchPage]);
  const handleSave = useCallback(
    async (doc) => {
      setEditedContents(doc.contents);
      await onSave(docs.map((n, idx) => idx === currentPage ? doc : n));
    },
    [currentPage, docs, onSave]
  );
  const handleDeletePage = useCallback(
    (deletePageNumber) => {
      onDelete == null ? void 0 : onDelete(deletePageNumber);
      setDeleteTarget(deletePageNumber);
    },
    [onDelete, setDeleteTarget]
  );
  const handleEditedDocs = useCallback((newContents) => {
    setEditedContents(newContents);
  }, []);
  useEffect(() => {
    if (docs.length === 0)
      return;
    if (currentPage < 0) {
      setCurrentPage(0);
      fireDocChangeSignal();
    }
    if (currentPage >= docs.length) {
      setCurrentPage(docs.length - 1);
      fireDocChangeSignal();
    }
  }, [currentPage, docs.length, fireDocChangeSignal]);
  useEffect(() => {
    setEditedContents((prev) => {
      var _a2;
      return ((_a2 = docs == null ? void 0 : docs[currentPage]) == null ? void 0 : _a2.contents) ?? prev;
    });
  }, [currentPage, docs]);
  const handleDropdown = useCallback(
    (pageNumber) => handleDeletePage(pageNumber),
    [handleDeletePage]
  );
  if (docs.length === 0) {
    return /* @__PURE__ */ jsx(
      Message,
      {
        description: /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsx("p", { children: "No documents for this project" }),
          !disabled && /* @__PURE__ */ jsx(Button, { onClick: handleNewPage, children: "+ New Document" })
        ] }),
        icon: "document"
      }
    );
  }
  return /* @__PURE__ */ jsxs("div", { className: themeClass, children: [
    /* @__PURE__ */ jsx(Column, { align: "right", children: !disabled && /* @__PURE__ */ jsx(Button, { type: "text", onClick: onNewPage, children: "+ New Doc" }) }),
    /* @__PURE__ */ jsxs("div", { className: css.base, children: [
      docs.length > 0 && /* @__PURE__ */ jsx("ul", { className: css.listContainer, role: "list", children: docs.map((doc, idx) => /* @__PURE__ */ jsx(
        Dropdown,
        {
          disabled,
          isContextMenu: true,
          menu: DROPDOWN_MENU,
          onClick: () => handleDropdown(idx),
          children: /* @__PURE__ */ jsx(
            "li",
            {
              className: css.listItem,
              style: {
                borderColor: idx === currentPage ? "var(--theme-stage-border-strong)" : void 0
              },
              onClick: () => handleSwitchPage(idx),
              children: /* @__PURE__ */ jsx(Surface, { hover: true, children: /* @__PURE__ */ jsxs(Row, { children: [
                /* @__PURE__ */ jsx("span", { children: doc.name }),
                /* @__PURE__ */ jsx(Column, { align: "right", children: !disabled && /* @__PURE__ */ jsx(Dropdown, { menu: DROPDOWN_MENU, onClick: () => handleDropdown(idx), children: /* @__PURE__ */ jsx("div", { className: css.action, onClick: (e) => e.stopPropagation(), children: /* @__PURE__ */ jsx(Icon, { name: "overflow-horizontal", title: "Action menu" }) }) }) })
              ] }) })
            }
          )
        },
        idx
      )) }),
      /* @__PURE__ */ jsx("div", { className: [css.pageSelectRow, themeClass].join(" "), children: /* @__PURE__ */ jsx(Select, { value: currentPage, onSelect: handleSwitchPage, children: docs.map((doc, idx) => {
        return /* @__PURE__ */ jsxs(Option, { value: idx, children: [
          /* @__PURE__ */ jsx(
            "span",
            {
              style: {
                marginRight: 8,
                visibility: idx === currentPage ? "visible" : "hidden"
              },
              children: /* @__PURE__ */ jsx(Icon, { name: "checkmark", size: "small", title: "Current document" })
            }
          ),
          /* @__PURE__ */ jsx("span", { children: doc.name })
        ] }, idx);
      }) }) }),
      /* @__PURE__ */ jsx("div", { className: css.docsContainer, children: /* @__PURE__ */ jsx(
        DocumentCard,
        {
          disabled,
          doc: docs == null ? void 0 : docs[currentPage],
          documentChangeSignal: docChangeSignal,
          extra: /* @__PURE__ */ jsx(Dropdown, { menu: DROPDOWN_MENU, onClick: () => handleDropdown(currentPage), children: /* @__PURE__ */ jsx(
            Button,
            {
              icon: /* @__PURE__ */ jsx(Icon, { name: "overflow-horizontal", title: "Action menu" }),
              type: "text"
            }
          ) }),
          onChange: handleEditedDocs,
          onError,
          onPageUnloadHook,
          onSaveDocument: handleSave
        }
      ) })
    ] })
  ] });
};
export {
  DocCards as default
};
