/*
 * Reset Button for Main Block
 */

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

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

const hasChanged = ( currentAttributes = {}, attributeKey, deviceType ) => {
	const attributeValue = currentAttributes[ attributeKey ];
	const defaultValue = defaultSettings[ attributeKey ];

	// Check if attributeValue and defaultValue are objects
	if ( typeof attributeValue === 'object' && attributeValue !== null && typeof defaultValue === 'object' && defaultValue !== null ) {
		return attributeValue[ deviceType ] !== defaultValue[ deviceType ];
	}

	// For non-object attributes, directly compare the values
	return attributeValue !== defaultValue;
};

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

const ResetButton = ( { currentAttributes, attributeKeys, setAttributes, label, deviceType } ) => {
	// Check if any attribute has changed for the current device type
	const isChanged = attributeKeys.some( ( key ) => hasChanged( currentAttributes, key, deviceType ) );

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

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

export default ResetButton;
