import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useState } from "react";
import { useEditContext } from "../client/editContext";
import { loadRenderingParametersSchema, } from "../services/editService";
import { Select } from "../../components";
function parseParameters(parameters) {
    const parsed = {};
    const searchParams = new URLSearchParams(parameters || "");
    for (const [key, value] of searchParams.entries()) {
        parsed[key] = value;
    }
    return parsed;
}
function isGuidLike(value) {
    return /^[{(]?[0-9a-fA-F-]{36}[)}]?$/.test((value || "").trim());
}
function normalizeGuidLike(value) {
    return (value || "")
        .replace(/[{}()]/g, "")
        .trim()
        .toLowerCase();
}
function formatGuidWithBraces(value) {
    const normalized = normalizeGuidLike(value);
    return normalized ? `{${normalized.toUpperCase()}}` : value;
}
function getSectionTitle(field) {
    return field.sectionTitle?.trim() || "General";
}
export function RenderingParametersSection({ component, pageItem, readonly = false, }) {
    const editContext = useEditContext();
    const [schema, setSchema] = useState();
    const [loading, setLoading] = useState(false);
    const [values, setValues] = useState({});
    const [savingField, setSavingField] = useState();
    const persistedValues = useMemo(() => parseParameters(component?.parameters), [component?.parameters]);
    useEffect(() => {
        let cancelled = false;
        async function loadSchema() {
            if (!component?.id || !component.parametersTemplateId || !pageItem) {
                setSchema(undefined);
                return;
            }
            setLoading(true);
            try {
                const nextSchema = await loadRenderingParametersSchema(pageItem, component.id);
                if (!cancelled) {
                    setSchema(nextSchema);
                }
            }
            catch (error) {
                console.error("Failed to load rendering parameters schema", error);
                if (!cancelled) {
                    setSchema(undefined);
                }
            }
            finally {
                if (!cancelled) {
                    setLoading(false);
                }
            }
        }
        loadSchema();
        return () => {
            cancelled = true;
        };
    }, [component?.id, component?.parametersTemplateId, pageItem]);
    useEffect(() => {
        setValues(persistedValues);
    }, [component?.id, persistedValues]);
    const fields = schema?.fields || [];
    const hasFields = loading || fields.length > 0;
    const saveParameter = async (field, value) => {
        const operations = editContext?.operations;
        if (!component?.id || readonly || !operations) {
            return;
        }
        const currentValue = persistedValues[field.name] ?? "";
        const nextComparable = value ?? "";
        if (currentValue === nextComparable) {
            return;
        }
        setSavingField(field.name);
        setValues((current) => {
            const next = { ...current };
            if (value == null) {
                delete next[field.name];
            }
            else {
                next[field.name] = value;
            }
            return next;
        });
        try {
            await operations.updateRenderingParameters(component.id, {
                [field.name]: value,
            });
        }
        finally {
            setSavingField((current) => current === field.name ? undefined : current);
        }
    };
    const sortedFields = useMemo(() => fields, [fields]);
    const groupedSections = useMemo(() => {
        const sectionsByTitle = new Map();
        const orderedSections = [];
        for (const field of sortedFields) {
            const title = getSectionTitle(field);
            let section = sectionsByTitle.get(title);
            if (!section) {
                section = { title, fields: [] };
                sectionsByTitle.set(title, section);
                orderedSections.push(section);
            }
            section.fields.push(field);
        }
        return orderedSections;
    }, [sortedFields]);
    if (!component?.parametersTemplateId || !hasFields) {
        return null;
    }
    return (_jsxs("section", { className: "border-border-default border-t px-3 py-3", "data-testid": "rendering-parameters-section", children: [_jsx("div", { className: "mb-3", children: _jsx("h3", { className: "text-neutral-grey-100 text-xs font-medium", children: "Rendering Parameters" }) }), loading && (_jsx("div", { className: "text-neutral-grey-50 text-xs", "data-testid": "rendering-parameters-loading", children: "Loading rendering parameters..." })), !loading && sortedFields.length === 0 && (_jsx("div", { className: "text-neutral-grey-50 text-xs", children: "No editable rendering parameters are available for this component." })), !loading && sortedFields.length > 0 && (_jsx("div", { className: "space-y-6", children: groupedSections.map((section) => (_jsxs("div", { className: "space-y-3", "data-testid": `rendering-parameter-section-${section.title.replace(/\s+/g, "-").toLowerCase()}`, children: [_jsx("div", { className: "border-border-default text-neutral-grey-50 border-b pb-1 text-xs font-semibold tracking-wide", children: section.title }), section.fields.map((field) => {
                            const value = values[field.name] ?? "";
                            const isSaving = savingField === field.name;
                            const disabled = readonly || isSaving;
                            const selectedOption = field.options.find((option) => {
                                if (option.id === value)
                                    return true;
                                if (isGuidLike(option.id) && isGuidLike(value)) {
                                    return (normalizeGuidLike(option.id) === normalizeGuidLike(value));
                                }
                                return false;
                            });
                            const selectOptions = field.options.map((option) => ({
                                value: option.id,
                                label: option.name,
                            }));
                            return (_jsxs("label", { className: "block", "data-testid": `rendering-parameter-field-${field.name}`, children: [_jsx("div", { className: "text-neutral-grey-100 mb-1 text-xs font-medium", children: field.title }), field.inputType === "checkbox" && (_jsx("input", { type: "checkbox", checked: value === "1" || value.toLowerCase() === "true", disabled: disabled, "data-testid": `rendering-parameter-input-${field.name}`, onChange: (event) => void saveParameter(field, event.target.checked ? "1" : "0") })), (field.inputType === "select" ||
                                        field.inputType === "droptree") && (_jsx(Select, { value: selectedOption?.id, disabled: disabled, "data-testid": `rendering-parameter-input-${field.name}`, options: selectOptions, placeholder: field.inputType === "droptree"
                                            ? "Select item"
                                            : "Select...", searchable: field.inputType === "droptree", emptyMessage: "No options available", onValueChange: (nextValue) => void saveParameter(field, isGuidLike(nextValue)
                                            ? formatGuidWithBraces(nextValue)
                                            : nextValue) })), field.inputType === "multiselect" && (_jsx("select", { multiple: true, className: "border-border-default badge-pad w-full rounded border text-xs", value: value ? value.split("|").filter(Boolean) : [], disabled: disabled, "data-testid": `rendering-parameter-input-${field.name}`, onChange: (event) => {
                                            const selectedValues = Array.from(event.target.selectedOptions).map((option) => option.value);
                                            void saveParameter(field, selectedValues.length > 0
                                                ? selectedValues.join("|")
                                                : null);
                                        }, children: field.options.map((option) => (_jsx("option", { value: option.id, children: option.name }, option.id))) })), field.inputType === "text" && (_jsx("input", { type: "text", className: "border-border-default badge-pad w-full rounded border text-xs", value: value, disabled: disabled, "data-testid": `rendering-parameter-input-${field.name}`, onChange: (event) => setValues((current) => ({
                                            ...current,
                                            [field.name]: event.target.value,
                                        })), onBlur: (event) => void saveParameter(field, event.target.value || null) }))] }, field.name));
                        })] }, section.title))) }))] }));
}
//# sourceMappingURL=RenderingParametersSection.js.map