"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OnePageWizard = exports.OnePageWizardContext = exports.FormDescriptionText = exports.SummaryText = exports.SummaryTag = void 0;
exports.useOnePageWizardContext = useOnePageWizardContext;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const react_1 = require("react");
const clsx_1 = tslib_1.__importDefault(require("clsx"));
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 Flex_1 = require("../../components/Flex");
const twMerge_1 = require("../../twMerge");
const twUtils_1 = require("../../components/twUtils");
const SummaryTag = (props) => (React.createElement(Flex_1.Box, { ...props }));
exports.SummaryTag = SummaryTag;
const SummaryText = (props) => (React.createElement(Flex_1.Box, { ...props, className: (0, twMerge_1.twMerge)('twa:text-2 twa:mb-3', props.className) }));
exports.SummaryText = SummaryText;
const FormDescriptionText = (props) => React.createElement(Flex_1.Box, { ...props, className: (0, twMerge_1.twMerge)('twa:text-2 twa:mt-1', props.className) });
exports.FormDescriptionText = FormDescriptionText;
exports.OnePageWizardContext = React.createContext({
    data: null,
    sections: [],
    setCurrentSection: (index) => { },
});
function useOnePageWizardContext() {
    return React.useContext(exports.OnePageWizardContext);
}
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;
    React.useEffect(() => {
        if (props.defaultCurrentSectionName) {
            const candidate = visibleSections.findIndex((section) => section !== '-' && section?.title === props.defaultCurrentSectionName);
            if (candidate >= 0) {
                setCurrentSection(candidate);
            }
        }
    }, [props.defaultCurrentSectionName, visibleSections]);
    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(Flex_1.Flex, { flexDirection: "column", key: index, "data-name": `section-${index}`, className: "twa:min-h-full twa:mr-2" },
            React.createElement(Flex_1.Box, { className: "ab-OnePageWizard__details twa:text-4 twa:py-3 twa:pl-2" }, section.details),
            React.createElement(Flex_1.Box, { className: "ab-OnePageWizard__section twa:flex-1 twa:rounded-standard twa:overflow-auto twa:bg-defaultbackground" }, section.render(props.data, index))));
    };
    const handleNavigation = (0, useKeyboardNavigation_1.useKeyboardNavigation)(setCurrentSection, visibleSections);
    const selectedNodeRef = (0, react_1.useRef)(null);
    const selectedFeedback = (React.createElement("div", { ref: selectedNodeRef, onKeyDown: (event) => handleNavigation(event), tabIndex: 0, className: (0, clsx_1.default)('ab-OnePageWizard__selected-title-overlay', 'twa:absolute twa:rounded-standard twa:select-none twa:bg-accent twa:transition-top twa:duration-200', twUtils_1.targetOwn.focusOutline) }));
    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`;
        node.focus();
    }, [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());
    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: props.modal ?? true, isOpen: true, showCloseButton: false, focusOnBrowserVisible: true, className: "twa:rounded-standard twa:overflow-hidden twa:h-[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(Flex_1.Box, { className: (0, clsx_1.default)('ab-OnePageWizard twa:flex twa:flex-col twa:h-full twa:w-[90vw] twa:max-w-[1200px]', 'twa:bg-primarylight twa:text-primary-foreground'), "data-name": props.name, style: props.style },
                    React.createElement(Flex_1.Flex, { flexDirection: "row", alignItems: "stretch", className: "twa:flex-1 twa:overflow-auto" },
                        React.createElement(Flex_1.Flex, { flexDirection: "column", className: "ab-OnePageWizard__section-title-container twa:p-3 twa:flex-none twa:overflow-auto twa:relative", ref: sizeOwnerRef, style: props.titleContainerStyle },
                            visibleSections.map((section, index) => {
                                if (section === '-') {
                                    return (React.createElement(Flex_1.Box, { as: "hr", className: "ab-OnePageWizard__section-separator twa:mt-2 twa:w-full twa:border-t twa:border-t-inputborder", key: `${index}-` }));
                                }
                                navIndex++;
                                navIndexMap.set(navIndex, index);
                                const active = index === currentSection;
                                const disabled = false; //!active && !currentSectionValid;
                                return (React.createElement(Flex_1.Flex, { className: (0, clsx_1.default)('ab-OnePageWizard__section-title twa:p-2', {
                                        'twa:cursor-auto': disabled,
                                        'twa:cursor-pointer': !disabled,
                                        'twa:z-10': true,
                                        'twa:opacity-50': disabled,
                                        'twa:opacity-100': !disabled,
                                        'twa:mt-2': index > 0,
                                        'twa:mt-0': index === 0,
                                        'twa:text-accent-foreground twa:pointer-events-none': active,
                                    }), "data-name": section.title, flexDirection: "row", style: {
                                        transition: 'color 0.2s',
                                    }, key: section.title, onClick: () => {
                                        if (disabled) {
                                            return;
                                        }
                                        if (active) {
                                            return;
                                        }
                                        setCurrentSection(index);
                                    } },
                                    React.createElement(KeyHint_1.KeyHint, { className: "twa:mr-2 twa:inline-block twa:text-color-accent-foreground" }, navIndex),
                                    React.createElement("div", { className: "twa:flex-1" }, section.title),
                                    React.createElement(icons_1.Icon, { name: "error", className: (0, clsx_1.default)('twa:ml-2', validSectionsMap.get(index) !== true ? 'twa:visible' : 'twa:invisible') })));
                            }),
                            selectedFeedback,
                            React.createElement(Flex_1.Box, { className: "twa:flex-1" }),
                            React.createElement(KeyHint_1.KeyHint, { className: "ab-OnePageWizard__key-hint twa:leading-normal" },
                                (0, isMacLike_1.isMacLike)() ? 'Cmd' : 'Ctrl',
                                " + #",
                                React.createElement("br", null),
                                "or arrow keys",
                                React.createElement("br", null),
                                "to navigate")),
                        React.createElement(Flex_1.Flex, { flexDirection: "column", className: "ab-OnePageWizard__section-container twa:flex-1" }, renderSection(currentSection))),
                    React.createElement(Flex_1.Flex, { flexDirection: "row", alignItems: "center", className: "ab-WizardDialog__footer ab-OnePageWizard__footer twa:p-2" },
                        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, { className: "twa:ml-2" }, "Esc"),
                        React.createElement(Flex_1.Box, { className: "ab-OnePageWizard__error twa:text-2 twa:mr-3 twa:flex-1 twa:text-error twa:text-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;
