"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OnePageWizard = exports.useOnePageWizardContext = exports.OnePageWizardContext = exports.FormDescriptionText = exports.SummaryText = exports.SummaryTag = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const react_1 = require("react");
const rebass_1 = require("rebass");
const Dialog_1 = tslib_1.__importDefault(require("../../components/Dialog"));
const SimpleButton_1 = tslib_1.__importDefault(require("../../components/SimpleButton"));
const useProperty_1 = tslib_1.__importDefault(require("../../components/utils/useProperty"));
const isMacLike_1 = require("../../Utilities/isMacLike");
const KeyHint_1 = require("../KeyHint");
const icons_1 = require("../../components/icons");
const ResizeObserver_1 = require("../../components/ResizeObserver");
const NamedQueryContext_1 = require("../../components/ExpressionEditor/NamedQueryContext");
const useKeyboardNavigation_1 = require("./useKeyboardNavigation");
const SummaryTag = (props) => (React.createElement(rebass_1.Text, { ...props }));
exports.SummaryTag = SummaryTag;
const SummaryText = (props) => (React.createElement(rebass_1.Text, { fontSize: 2, mb: 3, ...props }));
exports.SummaryText = SummaryText;
const FormDescriptionText = (props) => React.createElement(rebass_1.Text, { fontSize: 2, mt: 1, ...props });
exports.FormDescriptionText = FormDescriptionText;
exports.OnePageWizardContext = React.createContext({
    data: null,
    sections: [],
    setCurrentSection: (index) => { },
});
function useOnePageWizardContext() {
    return React.useContext(exports.OnePageWizardContext);
}
exports.useOnePageWizardContext = useOnePageWizardContext;
const OnePageWizard = (props) => {
    let defaultCurrentIndex = 0;
    const [currentSection, setCurrentSection] = (0, useProperty_1.default)(props, 'currentIndex', defaultCurrentIndex, {
        onChange: (index) => {
            props.onSectionChange?.(index);
        },
    });
    const contextValue = {
        data: props.data,
        sections: props.sections,
        setCurrentSection,
    };
    const visibleSections = React.useMemo(() => {
        return props.sections
            .filter(Boolean)
            .filter((section) => section === '-' ||
            section.isVisible == undefined ||
            section.isVisible(props.data, contextValue));
    }, [props.sections]);
    contextValue.sections = visibleSections;
    if (props.defaultCurrentSectionName) {
        const candidate = visibleSections.findIndex((section) => section !== '-' && section?.title === props.defaultCurrentSectionName);
        if (candidate >= 0) {
            defaultCurrentIndex = candidate;
        }
    }
    const [namedQuery, setNamedQuery] = (0, react_1.useState)(false);
    const [navIndexMap] = (0, react_1.useState)(() => new Map());
    const handleClickFinish = () => {
        props.onFinish?.(props.data);
    };
    const renderSection = (index) => {
        const section = visibleSections[index];
        if (section === '-') {
            return React.createElement(React.Fragment, { key: index });
        }
        return (React.createElement(rebass_1.Flex, { flexDirection: "column", key: index, "data-name": `section-${index}`, style: { minHeight: '100%' }, mr: 2 },
            React.createElement(rebass_1.Box, { py: 3, paddingLeft: 2, fontSize: 4, className: "ab-OnePageWizard__details" }, section.details),
            React.createElement(rebass_1.Box, { flex: 1, className: "ab-OnePageWizard__section" }, section.render(props.data, index))));
    };
    const selectedNodeRef = (0, react_1.useRef)(null);
    const selectedFeedback = (React.createElement("div", { ref: selectedNodeRef, className: "ab-OnePageWizard__selected-title-overlay", style: {
            position: 'absolute',
            background: 'var(--ab-cmp-one-page-wizard-selected-title__background)',
            pointerEvents: 'none',
            borderRadius: 'var(--ab__border-radius)',
            transition: 'top 0.2s',
        } }));
    const sizeOwnerRef = (0, react_1.useRef)(null);
    const [width, setWidth] = (0, react_1.useState)(0);
    (0, ResizeObserver_1.useResizeObserver)(sizeOwnerRef, ({ width }) => {
        setWidth(width);
    });
    React.useEffect(() => {
        const node = selectedNodeRef.current;
        const parent = node.parentNode;
        const activeElement = parent.children[currentSection];
        node.style.top = `${activeElement.offsetTop}px`;
        node.style.left = `${activeElement.offsetLeft}px`;
        node.style.height = `${activeElement.offsetHeight}px`;
        node.style.width = `${activeElement.offsetWidth}px`;
    }, [currentSection, width]);
    let navIndex = 0;
    const dialogRef = (0, react_1.useRef)(null);
    let invalidCount = 0;
    let firstErrorMessage = null;
    const validSectionsMap = visibleSections.reduce((acc, section, index) => {
        if (section === '-') {
            acc.set(index, true);
            return acc;
        }
        const valid = section.isValid ? section.isValid(props.data, contextValue) : true; //!active && canFinish !== true;
        if (valid !== true) {
            invalidCount++;
            if (firstErrorMessage == null) {
                firstErrorMessage = valid;
            }
        }
        acc.set(index, valid);
        return acc;
    }, new Map());
    (0, useKeyboardNavigation_1.useKeyboardNavigation)(setCurrentSection, visibleSections);
    const canFinish = !invalidCount;
    return (React.createElement(NamedQueryContext_1.NamedQueryContext.Provider, { value: { namedQuery, setNamedQuery } },
        React.createElement(exports.OnePageWizardContext.Provider, { value: contextValue },
            React.createElement(Dialog_1.default, { modal: true, isOpen: true, showCloseButton: false, focusOnBrowserVisible: true, style: {
                    borderRadius: 'var(--ab__border-radius)',
                    overflow: 'hidden',
                    height: '90vh',
                }, ref: dialogRef, onDismiss: () => props.onHide?.(), onKeyDown: (event) => {
                    if (event.metaKey || event.ctrlKey) {
                        const { key } = event;
                        if (!isNaN(Number(key))) {
                            const num = Number(key);
                            if (navIndexMap.has(num)) {
                                const index = navIndexMap.get(num);
                                setCurrentSection(index);
                                event.preventDefault();
                                event.stopPropagation();
                                requestAnimationFrame(() => {
                                    dialogRef?.current?.bringToFront();
                                });
                            }
                        }
                    }
                } },
                React.createElement(rebass_1.Flex, { className: "ab-OnePageWizard", flexDirection: "column", "data-name": props.name, style: {
                        height: '100%',
                        width: '90vw',
                        maxWidth: 1200,
                        ...props.style,
                    } },
                    React.createElement(rebass_1.Flex, { flexDirection: "row", alignItems: "stretch", flex: 1, style: { overflow: 'auto' } },
                        React.createElement(rebass_1.Flex, { flexDirection: "column", padding: 3, className: "ab-OnePageWizard__section-title-container", ref: sizeOwnerRef, style: {
                                overflow: 'auto',
                                position: 'relative',
                                flex: 'none',
                                ...props.titleContainerStyle,
                            } },
                            visibleSections.map((section, index) => {
                                if (section === '-') {
                                    return (React.createElement(rebass_1.Box, { as: "hr", mt: 2, className: "ab-OnePageWizard__section-separator", key: `${index}-`, style: {
                                            width: '100%',
                                            border: 'none',
                                            borderTop: `1px solid var(--ab-color-inputborder)`,
                                        } }));
                                }
                                navIndex++;
                                navIndexMap.set(navIndex, index);
                                const active = index === currentSection;
                                const disabled = false; //!active && !currentSectionValid;
                                return (React.createElement(rebass_1.Flex, { className: "ab-OnePageWizard__section-title", "data-name": section.title, flexDirection: "row", style: {
                                        cursor: disabled ? 'auto' : 'pointer',
                                        zIndex: 10,
                                        transition: 'color 0.2s',
                                        opacity: disabled ? 0.5 : 1,
                                    }, key: section.title, color: active ? 'var(--ab-cmp-one-page-wizard-section-title__color)' : '', px: 2, py: 1, mt: index ? 2 : 0, onClick: () => {
                                        if (disabled) {
                                            return;
                                        }
                                        setCurrentSection(index);
                                    } },
                                    React.createElement(KeyHint_1.KeyHint, { mr: 2, style: { display: 'inline-block' } }, navIndex),
                                    React.createElement("div", { style: { flex: 1 } }, section.title),
                                    React.createElement(icons_1.Icon, { name: "error", style: {
                                            marginLeft: 'var(--ab-space-2)',
                                            visibility: validSectionsMap.get(index) !== true ? 'visible' : 'hidden',
                                        } })));
                            }),
                            selectedFeedback,
                            React.createElement(rebass_1.Box, { flex: 1 }),
                            React.createElement(KeyHint_1.KeyHint, { style: { lineHeight: 1.5 }, className: "ab-OnePageWizard__key-hint" },
                                (0, isMacLike_1.isMacLike)() ? 'Cmd' : 'Ctrl',
                                " + #",
                                React.createElement("br", null),
                                "to navigate")),
                        React.createElement(rebass_1.Flex, { flex: 1, flexDirection: "column", className: "ab-OnePageWizard__section-container" }, renderSection(currentSection))),
                    React.createElement(rebass_1.Flex, { flexDirection: "row", padding: 2, alignItems: "center", className: "ab-WizardDialog__footer ab-OnePageWizard__footer" },
                        React.createElement(SimpleButton_1.default, { tone: "neutral", variant: "text", "data-name": "close", onClick: () => props.onHide?.(), tooltip: props.closeTooltip ?? 'Close wizard', accessLevel: 'Full' }, props.closeText ?? 'CLOSE'),
                        React.createElement(KeyHint_1.KeyHint, { ml: 2 }, "Esc"),
                        React.createElement(rebass_1.Text, { fontSize: 2, mr: 3, className: "ab-OnePageWizard__error", style: {
                                flex: 1,
                                color: 'var(--ab-color-error)',
                                textAlign: 'end',
                            } }, firstErrorMessage),
                        React.createElement(SimpleButton_1.default, { tone: "accent", "data-name": "finish", variant: "raised", disabled: canFinish !== true, onClick: () => handleClickFinish(), icon: 'check', accessLevel: 'Full' }, props.finishText ?? 'Finish')))))));
};
exports.OnePageWizard = OnePageWizard;
