import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "../../components/ui/dialog";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import DialogButtons from "./DialogButtons";
import { Button } from "../../components/ui/button";
import { Input } from "../../components/ui/input";
import { useEditContext } from "../client/editContext";
import { getChildren } from "../services/contentService";
import { useDebouncedCallback } from "use-debounce";
import { useItemNameValidation } from "../hooks/useParheliaSettings";
export function ItemNameDialog(props) {
    const editContext = useEditContext();
    const { validateItemName } = useItemNameValidation();
    const [name, setName] = useState(() => props?.name ?? "");
    const [validationError, setValidationError] = useState();
    const [isValid, setIsValid] = useState(false);
    const [isValidating, setIsValidating] = useState(false);
    const validationPromiseRef = useRef(null);
    const nameRef = useRef(null);
    useEffect(() => {
        setName(props?.name ?? "");
    }, [props?.name]);
    // Defer past Radix Dialog focus trap so the default name is visible and fully selected
    useLayoutEffect(() => {
        const t = window.setTimeout(() => {
            const el = nameRef.current;
            if (!el)
                return;
            el.focus({ preventScroll: true });
            el.select();
        }, 0);
        return () => window.clearTimeout(t);
    }, [props?.name]);
    // Handle Escape key to close dialog
    useEffect(() => {
        const handleEscape = (e) => {
            if (e.key === "Escape") {
                props.onClose?.(null);
            }
        };
        window.addEventListener("keydown", handleEscape);
        return () => {
            window.removeEventListener("keydown", handleEscape);
        };
    }, [props]);
    const checkName = async () => {
        setIsValidating(true);
        const trimmedName = name.trim();
        const validateAsItemName = props.validateAsItemName ?? true;
        const allowEmpty = props.allowEmpty ?? false;
        // Basic empty check
        if (trimmedName.length === 0) {
            if (allowEmpty) {
                setValidationError(undefined);
                setIsValid(true);
                setIsValidating(false);
                return true;
            }
            setIsValid(false);
            setValidationError("Name is required");
            setIsValidating(false);
            return false;
        }
        // Use settings-based validation
        if (validateAsItemName) {
            const settingsValidation = validateItemName(trimmedName);
            if (!settingsValidation.isValid) {
                setIsValid(false);
                setValidationError(settingsValidation.message);
                setIsValidating(false);
                return false;
            }
        }
        // Check for duplicate names if parent item is provided
        if (validateAsItemName && props.parentItem) {
            const children = await getChildren(props.parentItem.id, editContext?.sessionId ?? "", [], false, props.parentItem?.language || "en");
            if (children.find((x) => x.name.toLocaleLowerCase() === trimmedName.toLocaleLowerCase() &&
                (props.itemId ? x.id !== props.itemId : true))) {
                setIsValid(false);
                setValidationError("A page with this name already exists.");
                setIsValidating(false);
                return false;
            }
        }
        // All validations passed
        setValidationError(undefined);
        setIsValid(true);
        setIsValidating(false);
        return true;
    };
    const checkNameValidDebounced = useDebouncedCallback(async () => {
        const promise = checkName();
        validationPromiseRef.current = promise;
        await promise;
        // Clear the ref if this is still the current validation
        if (validationPromiseRef.current === promise) {
            validationPromiseRef.current = null;
        }
    }, 500);
    useEffect(() => {
        checkNameValidDebounced();
    }, [name]);
    const handleOk = async () => {
        // Wait for any pending validation to complete
        let isValidResult;
        if (validationPromiseRef.current) {
            isValidResult = await validationPromiseRef.current;
        }
        else {
            // If no validation is in progress, run it now
            isValidResult = await checkName();
        }
        // Only submit if validation passed
        if (isValidResult) {
            props.onClose?.(name);
        }
    };
    return (_jsx(Dialog, { open: true, onOpenChange: (open) => !open && props.onClose?.(null), children: _jsxs(DialogContent, { overlayClassName: "pointer-events-none", className: "sm:max-w-[420px]", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { children: props?.title ?? "Name" }), _jsx(DialogDescription, { children: props.message || "Enter a name for the new item:" })] }), _jsx("div", { className: "flex flex-col gap-4 px-8 pt-2 pb-6", children: _jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(Input, { ref: nameRef, value: name, className: "w-full", onChange: (e) => setName(e.target.value), onKeyDown: (ev) => {
                                    if (ev.key === "Enter" && isValid && !isValidating) {
                                        handleOk();
                                    }
                                    if (ev.key === "Escape")
                                        props.onClose?.(null);
                                } }), validationError && (_jsx("div", { className: "text-destructive animate-in fade-in slide-in-from-top-1 text-xs font-medium duration-200", children: validationError }))] }) }), _jsxs(DialogButtons, { hideBorder: true, className: "px-8 pt-0 pb-8", children: [_jsx(Button, { onClick: () => props.onClose?.(null), variant: "ghost", children: "Cancel" }), _jsx(Button, { onClick: handleOk, disabled: !isValid || isValidating, children: "Ok" })] })] }) }));
}
//# sourceMappingURL=ItemNameDialogNew.js.map