import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import { cn } from "../../lib/utils";
import { Button } from "./button";
import { X } from "lucide-react";
import { placeholderInputTypeRegistry } from "./PlaceholderInputTypes";
function parsePlaceholders(text) {
    const placeholders = [];
    // Match both {{placeholder}} and <<placeholder>> formats
    // Pattern: {{content}} or <<content>> where content cannot include braces/brackets
    const regex = /\{\{([^{}]+)\}\}|<<([^<>]+)>>/g;
    let match;
    let index = 0;
    while ((match = regex.exec(text)) !== null) {
        // match[1] is for {{placeholder}}, match[2] is for <<placeholder>>
        const placeholderContent = match[1] || match[2];
        if (placeholderContent) {
            // Parse the content: {{label|type|param=value|param2=value2}}
            const parts = placeholderContent.split("|");
            const label = parts[0]?.trim() || "";
            const type = parts[1]?.trim() || "text"; // Default to "text" type
            // Parse parameters from remaining parts (format: key=value)
            const parameters = {};
            for (let i = 2; i < parts.length; i++) {
                const part = parts[i]?.trim() || "";
                if (!part)
                    continue;
                const eqIndex = part.indexOf("=");
                if (eqIndex !== -1) {
                    const key = part.substring(0, eqIndex).trim();
                    const value = part.substring(eqIndex + 1).trim();
                    if (key) {
                        parameters[key] = value;
                    }
                }
            }
            placeholders.push({
                name: label,
                type,
                parameters,
                index: index++,
                startPos: match.index,
                endPos: match.index + match[0].length,
            });
        }
    }
    return placeholders;
}
export const PlaceholderInput = React.forwardRef(function PlaceholderInput({ text, onComplete, onCancel, className, showButtons = true, buttonsClassName, onFilledChange, }, ref) {
    const placeholders = parsePlaceholders(text);
    const [values, setValues] = React.useState({});
    // Create refs for each placeholder using useRef to avoid the null issue
    const inputRefs = React.useRef({});
    // Auto-focus first placeholder on mount
    React.useEffect(() => {
        if (placeholders.length > 0) {
            const firstInput = inputRefs.current[0];
            if (firstInput) {
                setTimeout(() => firstInput.focus(), 0);
            }
        }
    }, [placeholders.length]);
    // Check if all placeholders are filled
    const allFilled = placeholders.every((_, idx) => {
        const value = values[idx];
        return value !== undefined && value.trim() !== "";
    });
    // Notify parent when filled state changes
    React.useEffect(() => {
        onFilledChange?.(allFilled);
    }, [allFilled, onFilledChange]);
    const handleValueChange = (index, value) => {
        setValues((prev) => ({ ...prev, [index]: value }));
    };
    const handleSubmitInternal = React.useCallback(() => {
        // Build the filled text by replacing placeholders with values
        let filledText = text;
        // Replace in reverse order to maintain correct positions
        for (let i = placeholders.length - 1; i >= 0; i--) {
            const placeholder = placeholders[i];
            if (!placeholder)
                continue;
            const value = values[i] || "";
            // Format the value based on placeholder type and parameters
            let formattedValue = value;
            if (placeholder.type === "item" && value.includes("|")) {
                // Parse item value format: "id|path"
                const parts = value.split("|");
                const id = parts[0] || "";
                const path = parts[1] || "";
                const name = path.split("/").pop() || "";
                // For item placeholders, output ID and name without curly braces
                // to avoid being re-detected as a placeholder by the regex
                formattedValue = `[${id}] (${name})`;
            }
            filledText =
                filledText.substring(0, placeholder.startPos) +
                    formattedValue +
                    filledText.substring(placeholder.endPos);
        }
        onComplete(filledText);
    }, [text, placeholders, values, onComplete]);
    // Expose submit method to parent via ref
    React.useImperativeHandle(ref, () => ({
        submit: () => {
            if (allFilled) {
                handleSubmitInternal();
            }
        },
    }), [allFilled, handleSubmitInternal]);
    const handleKeyDown = (e, index) => {
        if (e.key === "Tab") {
            e.preventDefault();
            if (e.shiftKey) {
                // Shift+Tab: go to previous input (wrap to last if at first)
                const prevIndex = index - 1;
                if (prevIndex >= 0) {
                    inputRefs.current[prevIndex]?.focus();
                }
                else {
                    // Wrap to last placeholder
                    inputRefs.current[placeholders.length - 1]?.focus();
                }
            }
            else {
                // Tab: go to next input (wrap to first if at last)
                const nextIndex = index + 1;
                if (nextIndex < placeholders.length) {
                    inputRefs.current[nextIndex]?.focus();
                }
                else {
                    // Wrap to first placeholder
                    inputRefs.current[0]?.focus();
                }
            }
        }
        else if (e.key === "Enter") {
            e.preventDefault();
            handleSubmitInternal();
        }
        else if (e.key === "Escape") {
            e.preventDefault();
            onCancel?.();
        }
    };
    if (placeholders.length === 0) {
        // No placeholders, just display text
        return _jsx("div", { className: cn("text-xs", className), children: text });
    }
    // Build segments: text and placeholder inputs
    const segments = [];
    let lastPos = 0;
    placeholders.forEach((placeholder, idx) => {
        // Add text before this placeholder
        if (placeholder.startPos > lastPos) {
            segments.push(_jsx("span", { className: "inline-flex items-center whitespace-pre-wrap leading-6", children: text.substring(lastPos, placeholder.startPos) }, `text-${idx}`));
        }
        // Add input for this placeholder
        // Look up the component for this placeholder type
        const typeConfig = placeholderInputTypeRegistry.get(placeholder.type);
        const InputComponent = typeConfig?.component;
        if (InputComponent) {
            segments.push(_jsx(InputComponent, { placeholder: placeholder, value: values[idx] || "", onChange: (value) => handleValueChange(idx, value), onKeyDown: (e) => handleKeyDown(e, idx), inputRef: (el) => {
                    inputRefs.current[idx] = el;
                }, autoFocus: idx === 0 }, `input-${idx}`));
        }
        lastPos = placeholder.endPos;
    });
    // Add remaining text after last placeholder
    if (lastPos < text.length) {
        segments.push(_jsx("span", { className: "inline-flex items-center whitespace-pre-wrap leading-6", children: text.substring(lastPos) }, "text-end"));
    }
    return (_jsxs("div", { className: cn("space-y-2", className), children: [_jsxs("div", { className: cn("relative flex h-[80px] flex-wrap content-start items-center gap-1.5 overflow-y-auto rounded-lg border border-blue-200 bg-blue-50/50 p-3 text-xs", onCancel && "pr-8"), children: [segments, onCancel && (_jsx("button", { onClick: onCancel, className: "absolute top-2 right-2 rounded p-0.5 text-gray-400 transition-colors hover:bg-blue-100 hover:text-gray-600", title: "Cancel (Esc)", "aria-label": "Cancel", children: _jsx(X, { size: 14, strokeWidth: 2 }) }))] }), showButtons && (_jsxs("div", { className: cn("flex items-center gap-2", buttonsClassName), children: [_jsx(Button, { size: "sm", onClick: handleSubmitInternal, disabled: !allFilled, className: "h-7", children: "Submit" }), onCancel && (_jsx(Button, { size: "sm", variant: "ghost", onClick: onCancel, className: "h-7", children: "Cancel" })), !allFilled && (_jsx("span", { className: "text-xs text-gray-500", children: "Fill all fields (use Tab to navigate)" }))] }))] }));
});
//# sourceMappingURL=PlaceholderInput.js.map