import { BaseControl } from '@wordpress/components';
import { useInstanceId } from '@wordpress/compose';

const ConditionalField = ( {
	field,
	renderField,
	values,
	formValues,
	errors,
} ) => {
	const innerFields = field.fields ?? [];
	const instanceId = useInstanceId( ConditionalField, 'conditional-field' );
	const controlId = field?.id ?? field?.name ?? instanceId;

	if ( innerFields.length === 0 ) {
		return null;
	}

	if ( field.wrap === false ) {
		return innerFields.map( ( innerField ) =>
			renderField( innerField, {
				key: `${ field.name ?? field.id ?? 'conditional' }-${
					innerField.name ?? innerField.id
				}`,
				values,
				formValues,
				errors,
			} )
		);
	}

	return (
		<BaseControl
			id={ controlId }
			label={ field.label }
			help={ field.help }
			className="cliq-ui-conditional-field"
		>
			<div className={ `cliq-ui-conditional-fields${ field.columns > 1 ? ` has-${ field.columns }-columns` : '' }` }>
				{ innerFields.map( ( innerField ) =>
					renderField( innerField, {
						key: `${ field.name ?? field.id ?? 'conditional' }-${
							innerField.name ?? innerField.id
						}`,
						values,
						formValues,
						errors,
						fullWidth: innerField.fullWidth,
					} )
				) }
			</div>
		</BaseControl>
	);
};

export default ConditionalField;
