'use client';
import React, { useCallback, useEffect, useState } from 'react';
import { CodeEditor } from '../../../elements/CodeEditor/index.js';
import LabelComp from '../../Label/index.js';
import useField from '../../useField/index.js';
import { withCondition } from '../../withCondition/index.js';
import { fieldBaseClass } from '../shared.js';
const baseClass = 'json-field';
const JSONField = (props)=>{
    const { name, AfterInput, BeforeInput, Description, Error, Label: LabelFromProps, className, label, path: pathFromProps, readOnly, required, style, validate, width } = props;
    const Label = LabelFromProps || /*#__PURE__*/ React.createElement(LabelComp, {
        label: label,
        required: required
    });
    const editorOptions = 'editorOptions' in props ? props.editorOptions : {};
    const [stringValue, setStringValue] = useState();
    const [jsonError, setJsonError] = useState();
    const [hasLoadedValue, setHasLoadedValue] = useState(false);
    const memoizedValidate = useCallback((value, options)=>{
        if (typeof validate === 'function') return validate(value, {
            ...options,
            jsonError,
            required
        });
    }, [
        validate,
        required,
        jsonError
    ]);
    const { initialValue, // path,
    setValue, showError, value } = useField({
        path: pathFromProps || name,
        validate: memoizedValidate
    });
    const handleChange = useCallback((val)=>{
        if (readOnly) return;
        setStringValue(val);
        try {
            setValue(JSON.parse(val));
            setJsonError(undefined);
        } catch (e) {
            setJsonError(e);
        }
    }, [
        readOnly,
        setValue,
        setStringValue
    ]);
    useEffect(()=>{
        if (hasLoadedValue) return;
        setStringValue(JSON.stringify(value ? value : initialValue, null, 2));
        setHasLoadedValue(true);
    }, [
        initialValue,
        value,
        hasLoadedValue
    ]);
    return /*#__PURE__*/ React.createElement("div", {
        className: [
            fieldBaseClass,
            baseClass,
            className,
            showError && 'error',
            readOnly && 'read-only'
        ].filter(Boolean).join(' '),
        style: {
            ...style,
            width
        }
    }, Error, Label, /*#__PURE__*/ React.createElement("div", null, BeforeInput, /*#__PURE__*/ React.createElement(CodeEditor, {
        defaultLanguage: "json",
        onChange: handleChange,
        options: editorOptions,
        readOnly: readOnly,
        value: stringValue
    }), AfterInput), Description);
};
export default withCondition(JSONField);

//# sourceMappingURL=index.js.map