import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Icon } from "@powerhousedao/design-system";
import { exportDocument, setSelectedNode, setSelectedTimelineItem, showRevisionHistory, useGetSwitchboardLink, useNodeActions, useNodeParentFolderById, useSelectedDocumentSafe, } from "@powerhousedao/reactor-browser";
import { useEffect, useState } from "react";
import { twMerge } from "tailwind-merge";
import { DocumentTimeline } from "../document-timeline/document-timeline.js";
import { NodeInput } from "../node-input/node-input.js";
import { useDocumentUndoRedo } from "./utils/use-document-undo-redo.js";
// TODO: Remove this when timeline analytics is available
// import { useDocumentTimeline } from "@powerhousedao/reactor-browser/analytics";
function useDocumentTimeline(documentId) {
    return [];
}
export const DocumentToolbar = (props) => {
    const { onClose, children, onExport, className, document: _document, onSwitchboardLinkClick, enabledControls = ["undo", "redo", "export", "history"], defaultTimelineVisible = true, disableRevisionHistory = false, initialTimelineVisible = false, ...containerProps } = props;
    const [selectedDocument] = useSelectedDocumentSafe();
    const document = _document ?? selectedDocument;
    const { onRenameNode, onRenameDriveNodes } = useNodeActions();
    const documentName = document?.header.name || undefined;
    const [isEditingName, setIsEditingName] = useState(false);
    const parentFolder = useNodeParentFolderById(document?.header.id);
    const handleClose = onClose ?? (() => setSelectedNode(parentFolder));
    const handleExport = async (doc) => {
        if (!doc)
            return;
        if (onExport) {
            onExport(doc);
        }
        else {
            await exportDocument(doc);
        }
    };
    const documentUndoRedo = useDocumentUndoRedo(document?.header.id);
    const isUndoDisabled = !documentUndoRedo.canUndo;
    const isRedoDisabled = !documentUndoRedo.canRedo;
    const timelineItemsData = useDocumentTimeline(document?.header.id);
    const [showTimeline, setShowTimeline] = useState(initialTimelineVisible);
    const getSwitchboardLink = useGetSwitchboardLink(document);
    const handleDefaultSwitchboardClick = async () => {
        if (getSwitchboardLink) {
            try {
                const url = await getSwitchboardLink();
                window.open(url, "_blank");
            }
            catch (error) {
                console.error("Error opening switchboard link:", error);
            }
        }
    };
    const resolvedSwitchboardHandler = onSwitchboardLinkClick ??
        (getSwitchboardLink ? handleDefaultSwitchboardClick : undefined);
    const isExportDisabled = !document;
    const isSwitchboardLinkDisabled = !resolvedSwitchboardHandler;
    const isTimelineDisabled = timelineItemsData.length === 0;
    useEffect(() => {
        if (typeof initialTimelineVisible === "boolean") {
            setShowTimeline(initialTimelineVisible);
        }
    }, [initialTimelineVisible]);
    const handleTimelineToggle = () => {
        if (isTimelineDisabled)
            return;
        setShowTimeline(!showTimeline);
    };
    return (_jsxs("div", { className: "flex w-full flex-col", ...containerProps, children: [_jsxs("div", { className: twMerge("flex h-12 w-full items-center justify-between rounded-xl border border-gray-200 bg-slate-50 px-4", className), children: [_jsxs("div", { className: "flex items-center gap-x-2", children: [enabledControls.includes("undo") && (_jsx("button", { className: twMerge("grid size-8 place-items-center rounded-lg border border-gray-200 bg-white", isUndoDisabled
                                    ? "cursor-not-allowed"
                                    : "cursor-pointer active:opacity-70"), onClick: documentUndoRedo.undo, disabled: isUndoDisabled, children: _jsx(Icon, { name: "ArrowCouterclockwise", size: 16, className: isUndoDisabled ? "text-gray-500" : "text-gray-900" }) })), enabledControls.includes("redo") && (_jsx("button", { className: twMerge("grid size-8 place-items-center rounded-lg border border-gray-200 bg-white", isRedoDisabled
                                    ? "cursor-not-allowed"
                                    : "cursor-pointer active:opacity-70"), onClick: documentUndoRedo.redo, disabled: isRedoDisabled, children: _jsx("div", { className: "-scale-x-100", children: _jsx(Icon, { name: "ArrowCouterclockwise", size: 16, className: isRedoDisabled ? "text-gray-500" : "text-gray-900" }) }) })), enabledControls.includes("export") && (_jsx("button", { className: twMerge("flex h-8 items-center rounded-lg border border-gray-200 bg-white px-3 text-sm", isExportDisabled
                                    ? "cursor-not-allowed"
                                    : "cursor-pointer active:opacity-70"), onClick: () => void handleExport(document), disabled: isExportDisabled, children: _jsx("span", { className: isExportDisabled ? "text-gray-500" : "text-gray-900", children: "Export" }) }))] }), _jsx("div", { className: "flex items-center", children: isEditingName && document ? (_jsx(NodeInput, { defaultValue: documentName, className: "text-center text-sm font-medium text-gray-500", "aria-label": "Document name", onCancel: () => setIsEditingName(false), onSubmit: (newName) => {
                                const node = { id: document.header.id };
                                Promise.all([
                                    onRenameNode(newName, node),
                                    onRenameDriveNodes(newName, document.header.id),
                                ])
                                    .then(() => setIsEditingName(false))
                                    .catch((error) => {
                                    console.error("Failed to rename document:", error);
                                    setIsEditingName(false);
                                });
                            } })) : (_jsx("h1", { className: twMerge("text-sm font-medium text-gray-500", document && "cursor-pointer hover:text-gray-700"), onDoubleClick: document ? () => setIsEditingName(true) : undefined, title: document ? "Double-click to edit" : undefined, children: documentName })) }), _jsxs("div", { className: "flex items-center gap-x-2", children: [!isSwitchboardLinkDisabled && (_jsx("button", { className: twMerge("grid size-8 place-items-center rounded-lg border border-gray-200 bg-white", "cursor-pointer active:opacity-70"), onClick: resolvedSwitchboardHandler, disabled: isSwitchboardLinkDisabled, children: _jsx(Icon, { name: "Drive", size: 16, className: "text-gray-900" }) })), enabledControls.includes("history") && (_jsx("button", { className: twMerge("grid size-8 place-items-center rounded-lg border border-gray-200 bg-white", disableRevisionHistory
                                    ? "cursor-not-allowed"
                                    : "cursor-pointer active:opacity-70"), onClick: showRevisionHistory, disabled: disableRevisionHistory, children: _jsx(Icon, { name: "History", size: 16, className: disableRevisionHistory ? "text-gray-500" : "text-gray-900" }) })), enabledControls.includes("timeline") && defaultTimelineVisible && (_jsx("button", { className: twMerge("grid size-8 place-items-center rounded-lg border border-gray-200 bg-white", isTimelineDisabled
                                    ? "cursor-not-allowed"
                                    : "cursor-pointer active:opacity-70"), onClick: handleTimelineToggle, disabled: isTimelineDisabled, "aria-pressed": showTimeline, children: _jsx(Icon, { name: "Timeline", size: 16, className: twMerge("text-gray-900", isTimelineDisabled && "opacity-50", showTimeline && "text-blue-600") }) })), _jsx("button", { "aria-label": "Close document", className: "grid size-8 cursor-pointer place-items-center rounded-lg border border-gray-200 bg-white active:opacity-70", onClick: handleClose, children: _jsx(Icon, { name: "XmarkLight", size: 16, className: "text-gray-900" }) })] })] }), showTimeline && (_jsx("div", { className: "mt-2 w-full", children: _jsx(DocumentTimeline, { timeline: timelineItemsData, onItemClick: setSelectedTimelineItem }) })), children] }));
};
//# sourceMappingURL=document-toolbar.js.map