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

const RadioImageField = ( { field, value, onChange } ) => {
	const options = field.options ?? [];
	const instanceId = useInstanceId( RadioImageField, 'radio-image-field' );
	const controlId = field?.id ?? field?.name ?? instanceId;

	return (
		<BaseControl
			id={ controlId }
			label={ field.label }
			help={ field.help }
			required={ field.required }
		>
			<div className="cliq-ui-radio-image-group">
				{ options.map( ( option ) => {
					const optionValue = option.value ?? option.label;
					const isSelected = value === optionValue;

					return (
						<button
							key={ optionValue }
							type="button"
							className={ `cliq-ui-radio-image-option${
								isSelected ? ' is-selected' : ''
							}` }
							onClick={ () => onChange( optionValue ) }
						>
							{ option.image && (
								<img
									src={ option.image }
									alt={ option.label ?? optionValue }
								/>
							) }
							{ option.label && <span>{ option.label }</span> }
						</button>
					);
				} ) }
			</div>
		</BaseControl>
	);
};

export default RadioImageField;
