import { __ } from '@wordpress/i18n';
import { dispatch, select } from '@wordpress/data';
import blockConfig from '../block.json'; // Import main block config
import iconBlockConfig from '../icon-block/block.json'; // Import icon button block config

// Extract default settings from block.json for main and icon blocks
const defaultSettings = Object.fromEntries(
	Object.entries( blockConfig.attributes ).map( ( [ key, { default: defaultValue } ] ) => [ key, defaultValue ] )
);

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

const excludedAttributes = [
	'uniqueBlockButtonClass',
	'__internalWidgetId',
	'uniqueClass'
]; // Add other attributes you want to exclude

export const useCopyPasteBlockStyles = ( attributes, setAttributes, clientId ) => {
	const copyStyles = () => {
		const changedStyles = {};

		// Copy only the main block's changed attributes
		Object.keys( attributes ).forEach( ( key ) => {
			if ( attributes[ key ] !== defaultSettings[ key ] && !excludedAttributes.includes( key ) ) {
				changedStyles[ key ] = attributes[ key ];
			}
		} );

		// Get all inner blocks (e.g., icon button blocks)
		const innerBlocks = select( 'core/block-editor' ).getBlocks( clientId );
		const innerBlockStyles = innerBlocks.map( ( block ) => {
			const blockAttributes = block.attributes;
			const changedIconButtonStyles = {};

			// Copy changes only for icon button block attributes
			Object.keys( blockAttributes ).forEach( ( key ) => {
				if ( blockAttributes[ key ] !== defaultIconSettings[ key ] && !excludedAttributes.includes( key ) ) {
					changedIconButtonStyles[ key ] = blockAttributes[ key ];
				}
			} );

			return {
				clientId: block.clientId,
				blockName: block.name, // Make sure each block has a name
				styles: changedIconButtonStyles,
			};
		} );

		// Prepare the data to store in localStorage
		const dataToCopy = {
			blockName: 'smart-social-media-buttons/main', // Identifier for the main block
			clientId: clientId,
			styles: changedStyles,
			innerBlockStyles: innerBlockStyles, // Store inner block (icon button) styles
			timestamp: Date.now(), // Timestamp for expiration logic
		};

		localStorage.setItem( 'ssmbCopiedBlockStyles', JSON.stringify( dataToCopy ) );

		dispatch( 'core/notices' ).createNotice(
			'success',
			__( 'Styles copied!', 'smart-social-media-buttons' ),
			{ isDismissible: true, type: 'snackbar', duration: 3000 }
		);
	};

	const pasteStyles = () => {
		const copiedData = localStorage.getItem( 'ssmbCopiedBlockStyles' );
		if ( copiedData ) {
			const parsedCopiedData = JSON.parse( copiedData );
			const expirationDuration = 60 * 60 * 1000; // 1 hour
			const currentTime = Date.now();

			// Check if the copied styles have expired
			if ( currentTime - parsedCopiedData.timestamp > expirationDuration ) {
				localStorage.removeItem( 'ssmbCopiedBlockStyles' );
				dispatch( 'core/notices' ).createNotice(
					'warning',
					__( 'Copied styles have expired!', 'smart-social-media-buttons' ),
					{ isDismissible: true, type: 'snackbar', duration: 3000 }
				);
				return;
			}

			// Apply copied styles to the main block
			const parsedCopiedStyles = parsedCopiedData.styles;
			const updatedAttributes = { ...attributes };

			Object.keys( parsedCopiedStyles ).forEach( ( key ) => {
				if ( !excludedAttributes.includes( key ) ) {
					updatedAttributes[ key ] = parsedCopiedStyles[ key ];
				}
			} );

			setAttributes( updatedAttributes );

			// Get the inner blocks (icon buttons)
			const innerBlocks = select( 'core/block-editor' ).getBlocks( clientId );

			if ( innerBlocks.length > 0 ) {
				// Loop through the inner blocks and apply the copied styles to matching block types (icon buttons)
				innerBlocks.forEach( ( innerBlock, index ) => {
					if ( innerBlock.name === 'ssmb/icon-button' ) {
						// Find matching styles for the inner block (based on order or other criteria)
						const innerBlockStyles = parsedCopiedData.innerBlockStyles[ index ];

						if ( innerBlockStyles ) {
							const updatedInnerAttributes = { ...innerBlock.attributes };

							// Apply the styles to the inner block attributes
							Object.keys( innerBlockStyles.styles ).forEach( ( key ) => {
								if ( !excludedAttributes.includes( key ) ) {
									updatedInnerAttributes[ key ] = innerBlockStyles.styles[ key ];
								}
							} );

							// Dispatch the updated attributes to the inner block
							dispatch( 'core/block-editor' ).updateBlockAttributes( innerBlock.clientId, updatedInnerAttributes );
						}
					}
				} );
			}

			dispatch( 'core/notices' ).createNotice(
				'success',
				__( 'Styles pasted!', 'smart-social-media-buttons' ),
				{ isDismissible: true, type: 'snackbar', duration: 3000 }
			);
		} else {
			dispatch( 'core/notices' ).createNotice(
				'info',
				__( 'No styles copied!', 'smart-social-media-buttons' ),
				{ isDismissible: true, type: 'snackbar', duration: 3000 }
			);
		}
	};

	const isPasteEnabled = () => {
		const copiedData = localStorage.getItem( 'ssmbCopiedBlockStyles' );
		if ( !copiedData ) {
			return false;
		}

		const parsedCopiedData = JSON.parse( copiedData );

		// Check if the copied data is still valid (not expired and from the same block type)
		const expirationDuration = 60 * 60 * 1000; // 1 hour
		const currentTime = Date.now();

		if ( currentTime - parsedCopiedData.timestamp > expirationDuration ) {
			localStorage.removeItem( 'ssmbCopiedBlockStyles' );
			return false;
		}

		return parsedCopiedData.blockName === 'smart-social-media-buttons/main' && parsedCopiedData.clientId !== clientId;
	};

	return {
		copyStyles,
		pasteStyles,
		isPasteEnabled, // Return whether paste should be enabled or not
	};
};
