import CheckIcon from '../icons/CheckIcon';

/**
 * CheckboxButtonGroup
 * Renders the visual group of button-styled checkboxes.
 *
 * @param {Array} options - Array of objects { key: string, label: string }.
 * @param {Object} values - Associative object of selected keys { "key1": "1", ... }.
 * @param {Function} onChange - Callback (newValuesObject) => void.
 * @param {string} className - Optional extra classes.
 * @param {string} name - Optional name attribute for inputs (useful for accessibility/forms).
 */
const CheckboxButtonGroup = ( {options = [], values = {}, onChange, className = '', name = ''} ) => {

	const handleToggle = ( key ) => {
		const newValues = {...values};

		if ( newValues[key] ) {
			delete newValues[key];
		} else {
			newValues[key] = '1';
		}

		onChange( newValues );
	};

	return (
		<div className={`adpresso-checkbox-group-buttons ${className}`}>
			{options.map( ( option ) => {
				const key = option.key || option.value;
				const label = option.label;
				const isChecked = !!values[key];
				// generate an ID, if there is none, for a11y
				const inputId = name ? `${name}_${key}` : `cb_btn_${key}_${Math.random().toString( 36 ).substr( 2, 9 )}`;
				const labelClass = option.className || '';
				const disabled = option.disabled || false;

				return (
					<label
						key={key}
						htmlFor={inputId}
						className={`adpresso-checkbox-button ${isChecked ? 'is-checked' : ''} ${disabled ? 'is-disabled' : ''} ${labelClass}`}
					>
						<input
							type="checkbox"
							id={inputId}
							// Name is optional, but good for screenreader-grouping
							name={name ? `${name}[]` : undefined}
							className="adpresso-checkbox-input"
							checked={isChecked}
							onChange={() => handleToggle( key )}
							value="1"
							disabled={disabled}
						/>

						<CheckIcon width="13" height="13"/>
						<span className="adpresso-button-label">{label}</span>
					</label>
				);
			} )}
		</div>
	);
};

export default CheckboxButtonGroup;
