import FieldControl from '../components/FieldControl';
import {useMemo, useRef, useCallback} from '@wordpress/element';
import ConditionBuilder from '../../condition-builder/src/ConditionBuilder';

const ConditionsField = ( {field, value, onChange, availableConditions} ) => {
	// The saved value is a JSON string. We need to parse it.
	// We define a default structure if the value is empty or invalid.
	const initialTreeRef = useRef( {
		outer_connector: 'AND',
		groups:          [{id: `item_${Math.random().toString( 36 ).slice( 2, 9 )}`, conditions: []}]
	} );
	const parsedValue = useMemo( () => {
		try {
			if ( !value ) {
				return initialTreeRef.current;
			}
			if ( typeof value === 'string' ) {
				const p = JSON.parse( value );
				if ( p && Array.isArray( p.groups ) ) {
					return p;
				}
			} else if ( typeof value === 'object' && Array.isArray( value.groups ) ) {
				// If the parent returns an object.
				return value;
			}
		} catch ( e ) {
			console.error( 'Could not parse conditions JSON:', value, e );
		}
		return initialTreeRef.current;
	}, [value] );

	// If the condition tree changes, we serialize it back to a string.
	const handleTreeChange = useCallback( ( newTreeObject ) => {
		onChange( field.id, JSON.stringify( newTreeObject ) );
	}, [onChange, field.id] );

	return (
		<FieldControl
			label={field.label}
			help={field.description}
			id={field.id}
		>
			<ConditionBuilder
				value={parsedValue}
				onChange={handleTreeChange}
				availableConditions={availableConditions}
			/>
		</FieldControl>
	);
};

export default ConditionsField;
