import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Flex, IconBox, Switch, Text } from '@citric/core';
import { TimesCircle } from '@citric/icons';
import { listToClass } from '@stack-spot/portal-theme';
import { useTranslate } from '@stack-spot/portal-translate';
import { map } from 'lodash';
import { useCallback } from 'react';
import { JinjaRawContext, useJinjaContext } from '../context/JinjaContext.js';
import { errorDictionary } from '../dynamic/error-dictionary.js';
import { FormContextValue } from './FormContextValue.js';
import { FormObjectVariable, FormRepeatableVariable } from './FormVariable.js';
import { useFieldEffect, useFieldState, useFieldValue, useIsRepeating } from './hooks.js';
const RenderedInput = ({ variable, disabled, id, props }) => {
    const value = useFieldValue(variable);
    const config = variable.config;
    const context = useJinjaContext();
    if (!(context instanceof FormContextValue))
        throw new Error("Can't use a RenderedInput without a Form component");
    const onChange = useCallback(async (newValue) => {
        variable.set(newValue);
        if (!variable.getState().touched || !config.validation)
            return;
        variable.isValid(context);
    }, []);
    const onBlur = useCallback(async () => {
        if (variable.getState().touched)
            return;
        variable.isValid(context);
        variable.patchState({ touched: true });
    }, []);
    return _jsx(config.component, { ...props, id: id, name: config.name, value: value, onChange: onChange, disabled: disabled, onBlur: onBlur, variable: variable });
};
const RenderedRepeatableVariable = ({ variable, id, props }) => {
    const repeating = useIsRepeating(variable);
    return (_jsxs("div", { className: "repeatable-field", children: [_jsxs("div", { className: "field-header", children: [_jsxs(Flex, { alignItems: "center", justifyContent: "space-between", children: [_jsx(Text, { children: variable.config.label }), _jsxs("label", { children: [_jsx(Text, { children: "Repeat" }), _jsx(Switch, { checked: repeating, onChange: () => variable.setRepeating(!repeating) })] })] }), 'help' in variable.config && _jsx(Text, { className: "help", appearance: "microtext1", color: "light.700", children: variable.config.help })] }), repeating
                ? props.children
                : _jsx(RenderedVariable, { variable: variable.condensed, id: id, renderLabel: false, props: props })] }));
};
const RenderedVariable = (allProps) => {
    const { variable, id, renderLabel = !!variable.config.label, context, props: { children, ...props } } = allProps;
    const { disabled, visible, error } = useFieldState(variable);
    const t = useTranslate(errorDictionary);
    useFieldEffect(variable);
    if (!visible)
        return;
    const fieldHeader = (_jsxs("div", { className: "field-header", children: [_jsx(Text, { children: variable.config.label }), 'help' in variable.config && _jsx(Text, { className: "help", appearance: "microtext1", colorScheme: "light.700", children: variable.config.help })] }));
    function wrap(element) {
        return context ? _jsx(JinjaRawContext, { value: context, children: element }) : element;
    }
    if (variable instanceof FormRepeatableVariable) {
        return wrap(_jsx(RenderedRepeatableVariable, { variable: variable, id: id, props: { ...props, children } }));
    }
    // Object fields
    if (variable instanceof FormObjectVariable) {
        return wrap(_jsxs("div", { className: "field-object-group", children: [renderLabel && fieldHeader, children] }));
    }
    const input = (_jsx(RenderedInput, { id: id, variable: variable, props: props, disabled: disabled }));
    // Common fields
    return wrap(_jsxs("div", { className: listToClass(['field', error && 'error', disabled && 'disabled']), children: [renderLabel ? _jsxs("label", { children: [fieldHeader, input] }) : input, error && (_jsxs("div", { className: "error-message", children: [_jsx(IconBox, { className: "icon", children: _jsx(TimesCircle, {}) }), _jsx(Text, { children: t[error] || error })] }))] }));
};
export function buildFields(variables, context) {
    return map(variables, (variableList, key) => variableList.map((variable, index) => {
        const component = (props) => _jsx(RenderedVariable, { id: `${key}-${index}`, variable: variable, context: context, props: props }, `${key}-${index}`);
        component.variable = variable;
        if (variable instanceof FormObjectVariable) {
            component.fields = buildFields(variable.children);
        }
        else if (variable instanceof FormRepeatableVariable) {
            if (variable.condensed instanceof FormObjectVariable)
                component.fields = buildFields(variable.condensed.children);
            component.repeat = Object.keys(variable.expanded).map(key => buildFields(variable.expanded[key].variables, variable.expanded[key])).flat();
        }
        return component;
    })).flat();
}
//# sourceMappingURL=field-builder.js.map