import Modal, { ModalWidth } from "../Modal/Modal";
import Icon, { SizeProp } from "../Icon/Icon";
import IconProp from "../../../Types/Icon/IconProp";
import React, { useMemo, useState, } from "react";
import TemplateVariablesCatalog from "./TemplateVariablesCatalog";
/**
 * Modal that surfaces the dynamic template variables available to the
 * current monitor's incident/alert titles, descriptions, and
 * remediation notes. Organized by monitor type so a metric monitor
 * doesn't show SSL variables (and vice versa), with a live search
 * that scales when a user groups by many attributes.
 *
 * Click a variable to copy `{{var}}` to the clipboard; the chip flips
 * to a "Copied" state briefly so the user gets feedback without a
 * toast.
 */
const TemplateVariablesModal = (props) => {
    const [search, setSearch] = useState("");
    const [copiedKey, setCopiedKey] = useState(null);
    const groups = useMemo(() => {
        return TemplateVariablesCatalog.getVariables({
            monitorType: props.monitorType,
            seriesAttributeKeys: props.seriesAttributeKeys,
        });
    }, [props.monitorType, props.seriesAttributeKeys]);
    const normalized = search.trim().toLowerCase();
    const filteredGroups = useMemo(() => {
        if (!normalized) {
            return groups;
        }
        return groups
            .map((group) => {
            return Object.assign(Object.assign({}, group), { variables: group.variables.filter((v) => {
                    return (v.key.toLowerCase().includes(normalized) ||
                        v.description.toLowerCase().includes(normalized));
                }) });
        })
            .filter((group) => {
            return group.variables.length > 0;
        });
    }, [groups, normalized]);
    const copyToClipboard = (key) => {
        const token = `{{${key}}}`;
        if (typeof navigator !== "undefined" &&
            navigator.clipboard &&
            typeof navigator.clipboard.writeText === "function") {
            void navigator.clipboard.writeText(token);
        }
        setCopiedKey(key);
        setTimeout(() => {
            setCopiedKey((current) => {
                return current === key ? null : current;
            });
        }, 1500);
    };
    const renderVariableRow = (v) => {
        const isCopied = copiedKey === v.key;
        return (React.createElement("button", { key: v.key, type: "button", onClick: () => {
                copyToClipboard(v.key);
            }, className: "group w-full rounded-md border border-gray-200 bg-white px-3 py-2.5 text-left transition hover:border-indigo-300 hover:bg-indigo-50/40", title: `Click to copy {{${v.key}}}` },
            React.createElement("div", { className: "flex items-start justify-between gap-3" },
                React.createElement("div", { className: "min-w-0 flex-1" },
                    React.createElement("code", { className: "font-mono text-sm text-indigo-700 break-all" }, `{{${v.key}}}`),
                    React.createElement("p", { className: "mt-1 text-xs leading-snug text-gray-600" }, v.description),
                    v.example ? (React.createElement("p", { className: "mt-1 text-xs text-gray-400" },
                        "Example:",
                        " ",
                        React.createElement("span", { className: "font-mono text-gray-500" }, v.example))) : null),
                React.createElement("span", { className: `shrink-0 inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide transition ${isCopied
                        ? "bg-emerald-100 text-emerald-700"
                        : "bg-gray-100 text-gray-500 group-hover:bg-indigo-100 group-hover:text-indigo-700"}` }, isCopied ? "Copied" : "Copy"))));
    };
    const renderGroup = (group) => {
        return (React.createElement("div", { key: group.title, className: "space-y-2" },
            React.createElement("div", { className: "border-b border-gray-200 pb-1.5" },
                React.createElement("h3", { className: "text-sm font-semibold text-gray-900" }, group.title),
                group.description ? (React.createElement("p", { className: "mt-0.5 text-xs text-gray-500" }, group.description)) : null),
            group.variables.length > 0 ? (React.createElement("div", { className: "grid grid-cols-1 gap-2 sm:grid-cols-2" }, group.variables.map(renderVariableRow))) : (React.createElement("p", { className: "text-xs italic text-gray-400" }, "No variables in this section yet."))));
    };
    const totalVariables = groups.reduce((sum, group) => {
        return sum + group.variables.length;
    }, 0);
    return (React.createElement(Modal, { title: "Dynamic Template Variables", description: `Use these variables in incident and alert titles, descriptions, and remediation notes. Click any variable to copy it. ${totalVariables} variables available for this monitor type.`, onClose: props.onClose, onSubmit: props.onClose, submitButtonText: "Done", modalWidth: ModalWidth.Large },
        React.createElement("div", { className: "space-y-4" },
            React.createElement("div", { className: "relative" },
                React.createElement("div", { className: "pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3" },
                    React.createElement(Icon, { icon: IconProp.Search, size: SizeProp.Smaller, className: "h-4 w-4 text-gray-400" })),
                React.createElement("input", { type: "text", value: search, onChange: (e) => {
                        setSearch(e.target.value);
                    }, placeholder: "Filter variables\u2026", className: "block w-full rounded-md border border-gray-300 bg-white py-2 pl-9 pr-3 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500", autoFocus: true })),
            filteredGroups.length === 0 ? (React.createElement("div", { className: "rounded-md border border-gray-200 bg-gray-50 p-6 text-center text-sm text-gray-500" },
                "No variables match ",
                React.createElement("code", { className: "font-mono" }, search),
                ".")) : (React.createElement("div", { className: "space-y-5 max-h-[60vh] overflow-y-auto pr-1" }, filteredGroups.map(renderGroup))),
            React.createElement("div", { className: "rounded-md border border-blue-100 bg-blue-50 p-3 text-xs text-blue-900" },
                React.createElement("p", { className: "font-medium" }, "Syntax tips"),
                React.createElement("ul", { className: "mt-1 list-disc space-y-1 pl-4" },
                    React.createElement("li", null,
                        "Wrap the variable name in double braces:",
                        " ",
                        React.createElement("code", { className: "font-mono" }, "{{monitorName}}")),
                    React.createElement("li", null,
                        "Use dot paths for nested values:",
                        " ",
                        React.createElement("code", { className: "font-mono" }, "{{responseBody.data.status}}")),
                    React.createElement("li", null, "Missing values render as empty strings \u2014 they will not break the template."))))));
};
export default TemplateVariablesModal;
//# sourceMappingURL=TemplateVariablesModal.js.map