import * as React from 'react';
import { useState, useRef } from 'react';
import clsx from 'clsx';
import Dialog from '../../components/Dialog';
import SimpleButton from '../../components/SimpleButton';
import useProperty from '../../components/utils/useProperty';
import { isMacLike } from '../../Utilities/isMacLike';
import { KeyHint } from '../KeyHint';
import { Icon } from '../../components/icons';
import { useResizeObserver } from '../../components/ResizeObserver';
import { NamedQueryContext, } from '../../components/ExpressionEditor/NamedQueryContext';
import { useKeyboardNavigation } from './useKeyboardNavigation';
import { Box, Flex } from '../../components/Flex';
import { twMerge } from '../../twMerge';
import { targetOwn } from '../../components/twUtils';
export const SummaryTag = (props) => (React.createElement(Box, { ...props }));
export const SummaryText = (props) => (React.createElement(Box, { ...props, className: twMerge('twa:text-2 twa:mb-3', props.className) }));
export const FormDescriptionText = (props) => React.createElement(Box, { ...props, className: twMerge('twa:text-2 twa:mt-1', props.className) });
export const OnePageWizardContext = React.createContext({
    data: null,
    sections: [],
    setCurrentSection: (index) => { },
});
export function useOnePageWizardContext() {
    return React.useContext(OnePageWizardContext);
}
export const OnePageWizard = (props) => {
    let defaultCurrentIndex = 0;
    const [currentSection, setCurrentSection] = useProperty(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] = useState(false);
    const [navIndexMap] = 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, { flexDirection: "column", key: index, "data-name": `section-${index}`, className: "twa:min-h-full twa:mr-2" },
            React.createElement(Box, { className: "ab-OnePageWizard__details twa:text-4 twa:py-3 twa:pl-2" }, section.details),
            React.createElement(Box, { className: "ab-OnePageWizard__section twa:flex-1 twa:rounded-standard twa:overflow-auto twa:bg-defaultbackground" }, section.render(props.data, index))));
    };
    const handleNavigation = useKeyboardNavigation(setCurrentSection, visibleSections);
    const selectedNodeRef = useRef(null);
    const selectedFeedback = (React.createElement("div", { ref: selectedNodeRef, onKeyDown: (event) => handleNavigation(event), tabIndex: 0, className: clsx('ab-OnePageWizard__selected-title-overlay', 'twa:absolute twa:rounded-standard twa:select-none twa:bg-accent twa:transition-top twa:duration-200', targetOwn.focusOutline) }));
    const sizeOwnerRef = useRef(null);
    const [width, setWidth] = useState(0);
    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 = 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.Provider, { value: { namedQuery, setNamedQuery } },
        React.createElement(OnePageWizardContext.Provider, { value: contextValue },
            React.createElement(Dialog, { 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(Box, { className: clsx('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, { flexDirection: "row", alignItems: "stretch", className: "twa:flex-1 twa:overflow-auto" },
                        React.createElement(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(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, { className: clsx('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, { className: "twa:mr-2 twa:inline-block twa:text-color-accent-foreground" }, navIndex),
                                    React.createElement("div", { className: "twa:flex-1" }, section.title),
                                    React.createElement(Icon, { name: "error", className: clsx('twa:ml-2', validSectionsMap.get(index) !== true ? 'twa:visible' : 'twa:hidden') })));
                            }),
                            selectedFeedback,
                            React.createElement(Box, { className: "twa:flex-1" }),
                            React.createElement(KeyHint, { className: "ab-OnePageWizard__key-hint twa:leading-normal" },
                                isMacLike() ? 'Cmd' : 'Ctrl',
                                " + #",
                                React.createElement("br", null),
                                "or arrow keys",
                                React.createElement("br", null),
                                "to navigate")),
                        React.createElement(Flex, { flexDirection: "column", className: "ab-OnePageWizard__section-container twa:flex-1" }, renderSection(currentSection))),
                    React.createElement(Flex, { flexDirection: "row", alignItems: "center", className: "ab-WizardDialog__footer ab-OnePageWizard__footer twa:p-2" },
                        React.createElement(SimpleButton, { tone: "neutral", variant: "text", "data-name": "close", onClick: () => props.onHide?.(), tooltip: props.closeTooltip ?? 'Close wizard', accessLevel: 'Full' }, props.closeText ?? 'CLOSE'),
                        React.createElement(KeyHint, { className: "twa:ml-2" }, "Esc"),
                        React.createElement(Box, { className: "ab-OnePageWizard__error twa:text-2 twa:mr-3 twa:flex-1 twa:text-error twa:text-end" }, firstErrorMessage),
                        React.createElement(SimpleButton, { tone: "accent", "data-name": "finish", variant: "raised", disabled: canFinish !== true, onClick: () => handleClickFinish(), icon: 'check', accessLevel: 'Full' }, props.finishText ?? 'Finish')))))));
};
