import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useMemo, useState } from "react";
import { ScrollingContentTree } from "../editor/ScrollingContentTree";
import { getChildren, } from "../editor/services/contentService";
import { executeCreateItem, loadInsertOptions, } from "../editor/services/editService";
import { Input } from "../components/ui/input";
import { getAbsoluteIconUrl, getItemDescriptor } from "../editor/utils";
import { cn } from "../lib/utils";
import { useEditContext } from "../client-components";
import { useDebouncedCallback } from "use-debounce";
// Wizard imports removed; use generic insert options only
import { Card } from "../components/ui/card";
import { CardConnector } from "../components/ui/CardConnector";
import { ActionButton } from "../components/ActionButton";
import { FilePenLine, Palette, X, MapPin } from "lucide-react";
import { toast } from "sonner";
import { tourScrollIntoViewMarginClass } from "../tour/Tour";
export function NewPage({ selectedItemId, onClose, }) {
    const [selectedItem, setSelectedItem] = useState(null);
    const [isValid, setIsValid] = useState(false);
    const [insertOptions, setInsertOptions] = useState(null);
    const [validationMessage, setValidationMessage] = useState(null);
    const [selectedTemplate, setSelectedTemplate] = useState();
    const [name, setName] = useState("");
    const editContext = useEditContext();
    const insertOptionsAndWizards = useMemo(() => insertOptions || [], [insertOptions]);
    const selectedOption = useMemo(() => insertOptionsAndWizards?.find((x) => (x.id ?? x.typeId) === selectedTemplate), [insertOptionsAndWizards, selectedTemplate]);
    useEffect(() => {
        const loadOptions = async () => {
            if (!selectedItem)
                return;
            const item = getItemDescriptor(selectedItem);
            const insertOptions = await loadInsertOptions(item);
            // Keep all options (templates and wizards). Wizards have an `action` property.
            setInsertOptions(insertOptions);
            const firstOption = insertOptions?.[0];
            setSelectedTemplate(firstOption?.id ?? firstOption?.typeId);
        };
        loadOptions();
    }, [selectedItem]);
    useEffect(() => {
        const loadItem = async () => {
            const itemId = selectedItemId ||
                editContext?.item?.id ||
                editContext?.configuration.editor.dialogs.newPage.expandTreeNode;
            if (!itemId)
                return;
            const item = await editContext.itemsRepository.getItem({
                id: itemId,
                language: "en",
                version: 0,
            });
            if (item)
                setSelectedItem(item);
        };
        loadItem();
    }, [selectedItemId, editContext]);
    const isValidDebounced = useDebouncedCallback(async () => {
        if (!selectedItem)
            return;
        // Only validate for template creation (no action).
        const isWizard = !!selectedOption
            ?.action?.type;
        if (isWizard) {
            setIsValid(false);
            setValidationMessage(null);
            return;
        }
        let valid = !!selectedTemplate && name.trim().length >= 3;
        if (valid) {
            const children = await getChildren(selectedItem.id, editContext?.sessionId ?? "", [], false, editContext?.item?.language || "en");
            if (children.find((x) => x.name.toLocaleLowerCase() === name.trim().toLocaleLowerCase())) {
                valid = false;
                setValidationMessage("A page with this name already exists.");
            }
        }
        else {
            if (name.trim().length > 0 && name.trim().length < 3)
                setValidationMessage("Name is too short.");
            else
                setValidationMessage(null);
        }
        if (valid)
            setValidationMessage(null);
        setIsValid(valid);
    }, 200);
    useEffect(() => {
        isValidDebounced();
    }, [name, isValidDebounced]);
    const handleOk = async () => {
        if (!selectedItem || !selectedTemplate)
            return;
        const result = await executeCreateItem(getItemDescriptor(selectedItem), selectedTemplate, name, editContext?.sessionId);
        if (result.response.ok) {
            if (onClose) {
                onClose();
            }
            editContext?.switchWorkspace("editor");
            if (result.data)
                editContext?.loadItem(result.data);
        }
        else {
            toast.error("Failed to create item");
        }
    };
    return (_jsxs("div", { className: "flex h-full flex-col gap-6 overflow-y-auto bg-gray-100 p-4 md:p-8", children: [_jsxs("div", { className: "flex items-center justify-between gap-4", children: [_jsx("div", { className: "flex items-center gap-4", children: _jsxs("div", { className: "text-neutral-800", children: [_jsx("div", { className: "bg-linear-to-r from-slate-900 to-slate-600 bg-clip-text text-lg font-bold tracking-tight text-transparent md:text-3xl", children: "Create New Page" }), _jsx("div", { className: "mt-1 text-xs font-medium text-slate-500 md:text-sm", children: "Select a location, choose a template or wizard, and name your new page" })] }) }), _jsxs("div", { className: "mr-8 flex items-start gap-2", children: [!onClose && (_jsx(ActionButton, { onClick: () => editContext?.switchWorkspace("open-page"), children: "Open Existing" })), !onClose && (_jsx(ActionButton, { onClick: () => {
                                    // If previous view is also a modal (new-page/open-page), go back to home
                                    const prevWorkspace = editContext?.previousWorkspaceId;
                                    const targetWorkspace = prevWorkspace === "new-page" || prevWorkspace === "open-page"
                                        ? "home"
                                        : prevWorkspace || "home";
                                    editContext?.switchWorkspace(targetWorkspace);
                                }, variant: "ghost", className: "p-2", "aria-label": "Close", children: _jsx(X, { className: "h-4 w-4" }) }))] })] }), _jsxs("div", { className: "flex min-h-0 flex-1 flex-col md:flex-row", children: [" ", _jsx("div", { className: cn("tour-pick-location flex w-full flex-col md:w-80 lg:w-96", tourScrollIntoViewMarginClass), children: _jsx(Card, { icon: _jsx(MapPin, { className: "h-4 w-4" }), title: "Pick Location", description: "Select where to create your new page", noPadding: true, className: "flex flex-1 flex-col overflow-hidden", children: _jsx("div", { className: "flex min-h-0 flex-1 flex-col px-4 pb-4 md:px-6", children: _jsxs("div", { "data-testid": "new-page-pick-location-tree", className: "relative h-full min-h-[40vh] flex-1", children: [" ", _jsx("div", { className: "absolute inset-0 overflow-y-auto", children: _jsx(ScrollingContentTree, { selectedItemId: selectedItem?.id || selectedItemId, expandedItemId: selectedItem?.id || selectedItemId, scrollToSelected: true, hideRootNodes: true, onSelectionChange: (selection) => {
                                                    const selected = selection[0];
                                                    if (selected)
                                                        setSelectedItem(selected);
                                                } }) })] }) }) }) }), selectedItem && _jsx(CardConnector, {}), selectedItem && (_jsxs("div", { className: "flex w-full flex-1 flex-col md:h-full md:overflow-y-auto", children: [_jsx("div", { "data-testid": "new-page-template-section", children: _jsx(Card, { icon: _jsx(Palette, { className: "h-4 w-4" }), title: "Choose Template or Wizard", description: "Select a template or wizard to create your page", children: _jsx("div", { className: "tour-choose-template md:max-h-[400px] md:overflow-y-auto", children: _jsxs("div", { className: "grid grid-cols-[repeat(auto-fill,minmax(136px,1fr))] gap-3", children: [!insertOptions?.length && (_jsx("div", { className: "col-span-full text-sm text-gray-500", children: "You cannot insert content at the selected location." })), insertOptionsAndWizards?.map((option) => (_jsxs("div", { "data-testid": `template-option-${option.name}`, onClick: () => {
                                                        const id = option.id ?? option.typeId;
                                                        setSelectedTemplate(id);
                                                        const action = option.action;
                                                        if (action?.type && selectedItem) {
                                                            const cfg = editContext?.configuration;
                                                            const cmd = cfg?.commands?.[action.type] ||
                                                                cfg?.commands?.["start-wizard"];
                                                            if (cmd) {
                                                                editContext?.executeCommand({
                                                                    command: cmd,
                                                                    data: {
                                                                        ...(action.data ?? {}),
                                                                        item: selectedItem,
                                                                    },
                                                                });
                                                                if (onClose)
                                                                    onClose();
                                                            }
                                                        }
                                                    }, className: cn("hover:border-theme-secondary flex h-28 cursor-pointer flex-col items-center justify-center gap-2 rounded border border-gray-200 p-2 text-center text-[11px] transition-colors", tourScrollIntoViewMarginClass, selectedTemplate ===
                                                        (option.id ?? option.typeId)
                                                        ? "bg-theme-secondary-light border-theme-secondary shadow-sm"
                                                        : "bg-white"), children: [_jsx("img", { src: getAbsoluteIconUrl(option.icon), alt: option.name, width: "32", height: "32", className: "shrink-0" }), _jsx("span", { className: "line-clamp-2 leading-tight font-medium", children: option.name })] }, option.id ?? option.typeId)))] }) }) }) }), selectedTemplate &&
                                selectedOption &&
                                !selectedOption.action && (_jsxs(_Fragment, { children: [_jsx(CardConnector, { direction: "vertical" }), _jsx(Card, { icon: _jsx(FilePenLine, { className: "h-4 w-4" }), title: "Name Your Page", description: "Enter a name for your new page", className: "mb-4 md:mb-0", children: _jsxs("div", { children: [_jsx(Input, { className: cn("w-full rounded p-1.5 text-xs", tourScrollIntoViewMarginClass), value: name, id: "new-page-name", onChange: (e) => setName(e.target.value), onKeyDown: (ev) => {
                                                        if (ev.key === "Enter" && isValid)
                                                            handleOk();
                                                    }, "data-testid": "new-page-name", placeholder: "Enter page name..." }), validationMessage && (_jsx("div", { className: "mt-2 text-xs text-red-500", children: validationMessage })), _jsx("div", { className: "mt-4", children: _jsx(ActionButton, { id: "create-new-page-button", onClick: handleOk, disabled: !isValid, isLoading: false, className: tourScrollIntoViewMarginClass, children: "Create page" }) })] }) })] }))] }))] })] }));
}
//# sourceMappingURL=NewPage.js.map