/*
 * Reset Button for Icon Button Block
 */

import { Button } from '@wordpress/components';
import { RotateLeftIcon } from './constants/Icons';
import { __ } from '@wordpress/i18n';
import blockConfig from '../icon-block/block.json'; // Icon button block config

const defaultSettings = Object.fromEntries(
	Object.entries( blockConfig.attributes ).map( ( [ key, { default: defaultValue } ] ) => [ key, defaultValue ] )
);

const hasChanged = ( currentAttributes = {}, attributeKeys = [] ) => {
	return attributeKeys.some( ( key ) => currentAttributes[ key ] !== defaultSettings[ key ] );
};

const resetAttributes = ( attributeKeys, setAttributes ) => {
	const resetValues = attributeKeys.reduce( ( acc, key ) => {
		acc[ key ] = defaultSettings[ key ];
		return acc;
	}, {} );
	setAttributes( resetValues );
};

const ResetIconButton = ( { currentAttributes, attributeKeys, setAttributes, label, onPanelChange } ) => {
	const isChanged = hasChanged( currentAttributes, attributeKeys );

	const buttonClass = `ssmb-reset-button ${isChanged ? 'has-changed' : ''}`;

	// Notify panel of change
	if ( onPanelChange ) {
		onPanelChange( isChanged );
	}

	return (
		<Button
			className={ buttonClass }
			icon = { <RotateLeftIcon /> }
			label = { label }
			onClick = { () => resetAttributes( attributeKeys, setAttributes ) }
			disabled = { !isChanged }
		/>
	);
};

export default ResetIconButton;
