import { __ } from '@wordpress/i18n';
import { dispatch } from '@wordpress/data';
import blockConfig from '../icon-block/block.json'; // Import the icon-block's block config

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

const excludedAttributes = [
	'uniqueBlockButtonClass',
	'__internalWidgetId',
	'uniqueBlockButtonClass',
	'buttonIcon',
	'isFontAwesome',
	'buttonIconLink',
	'linkRel',
	'openInNewTab',
	'linkTitle'
]; // Add any other attributes you want to exclude

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

		// Copy only the attributes that have changed and are not in the excluded list
		Object.keys( attributes ).forEach( ( key ) => {
			if ( attributes[ key ] !== defaultSettings[ key ] && !excludedAttributes.includes( key ) ) {
				changedStyles[ key ] = attributes[ key ];
			}
		} );

		// Only store if there are actually changed styles
		if ( Object.keys( changedStyles ).length > 0 ) {
			const blockName = 'ssmb/icon-button'; // Use the block name from block.json

			const dataToCopy = {
				blockName: blockName, // Store the block name
				clientId: clientId,
				styles: changedStyles,
				timestamp: Date.now(), // Add timestamp for expiration logic
			};

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

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

	const pasteStyles = () => {
		const copiedData = localStorage.getItem( 'ssmbCopiedButtonStyles' );
		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( 'ssmbCopiedButtonStyles' );
				dispatch( 'core/notices' ).createNotice(
					'warning',
					__( 'Copied button styles have expired!', 'smart-social-media-buttons' ),
					{ isDismissible: true, type: 'snackbar', duration: 3000 }
				);
				return;
			}

			// Ensure the block name matches before pasting
			if ( parsedCopiedData.blockName !== 'ssmb/icon-button' ) {
				dispatch( 'core/notices' ).createNotice(
					'error',
					__( 'Cannot paste styles from a different block type!', 'smart-social-media-buttons' ),
					{ isDismissible: true, type: 'snackbar', duration: 3000 }
				);
				return;
			}

			// Prevent pasting on the same block where styles were copied
			if ( clientId === parsedCopiedData.clientId ) {
				dispatch( 'core/notices' ).createNotice(
					'warning',
					__( 'Cannot paste styles to the same button block!', 'smart-social-media-buttons' ),
					{ isDismissible: true, type: 'snackbar', duration: 3000 }
				);
				return;
			}

			const parsedCopiedStyles = parsedCopiedData.styles;

			// Apply copied styles directly to button attributes
			const updatedAttributes = { ...attributes };

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

			setAttributes( updatedAttributes );

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

	const isPasteEnabled = () => {
		const copiedData = localStorage.getItem( 'ssmbCopiedButtonStyles' );
		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( 'ssmbCopiedButtonStyles' );
			return false;
		}

		// Check if the block name and clientId match
		return parsedCopiedData.blockName === 'ssmb/icon-button' && parsedCopiedData.clientId !== clientId;
	};

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