/**
 * External dependencies.
 */
import {
	__experimentalVStack as VStack,
	__experimentalHStack as HStack,
	ToggleControl,
	Button,
} from '@wordpress/components';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies.
 */
import DynamicImage from '@spectra-pro-extensions/dynamic-content/components/DynamicImage';
import { DynamicContentProvider } from '@spectra-pro-extensions/dynamic-content/context/DynamicContentContext';
import { getDynamicContent } from '@spectra-pro-extensions/dynamic-content/utils/helpers';
import DynamicLink from '@spectra-pro-extensions/dynamic-content/components/DynamicLink';
import { PopoverCloseContext } from '@spectra-pro-extensions/dynamic-content/components/ImageFields/FallbackImage';

/**
 * Content component for the dynamic image toolbar popover.
 *
 * Provides controls to toggle dynamic image and link support, manage dynamic
 * content settings, and handle attribute updates for the core/image block within
 * a compact popover format suitable for the toolbar.
 *
 * @since x.x.x
 *
 * @param {Object}   props               - The component props.
 * @param {string}   props.blockName     - The name of the block (e.g., 'core/image').
 * @param {Object}   props.attributes    - The block's attributes.
 * @param {Function} props.setAttributes - Function to update block attributes.
 * @param {Function} props.onClose       - Function to close the popover.
 * @return {Element} The dynamic image toolbar content.
 */
const DynamicImageToolbarContent = ( props ) => {
	const { blockName, attributes, setAttributes, onClose, popoverRef } = props;

	const {
		spectraProEnableDynamicImage,
		spectraProStaticImage,
		spectraProDynamicImage,
		spectraProEnableDynamicLink,
		href,
	} = attributes;

	/**
	 * Handles toggling the dynamic image feature.
	 *
	 * Updates block attributes to enable or disable dynamic images, fetching dynamic
	 * content when enabling or restoring static image when disabling.
	 *
	 * @param {boolean} newValue - The new toggle state.
	 */
	const handleImageToggle = async ( newValue ) => {
		if ( newValue ) {
			if ( spectraProDynamicImage ) {
				// Re-enable dynamic image and fetch content if settings exist.
				const dynamicImage = await getDynamicContent( spectraProDynamicImage, 'image' );

				if ( dynamicImage?.url ) {
					setAttributes( {
						spectraProEnableDynamicImage: true,
						url: dynamicImage.url,
						id: dynamicImage.id,
					} );

					// Store current static image if not already set.
					if ( ! spectraProStaticImage ) {
						setAttributes( {
							spectraProStaticImage: {
								id: attributes.id,
								url: attributes.url,
								type: attributes.type,
							},
						} );
					}
					return;
				}
			}

			// If no dynamic image or fetch failed
			setAttributes( {
				spectraProEnableDynamicImage: true,
			} );
		} else {
			// Disabling dynamic image: restore static image and clear dynamic settings.
			setAttributes( {
				spectraProEnableDynamicImage: false,
				spectraProDynamicImage: null, // Clear dynamic image settings
				url: spectraProStaticImage?.url,
				id: spectraProStaticImage?.id,
			} );
		}
	};

	/**
	 * Handles toggling the dynamic link feature.
	 *
	 * Updates block attributes to enable or disable dynamic links, setting a placeholder
	 * href when enabling or clearing it when disabling if applicable.
	 */
	const handleLinkToggle = () => {
		const newValue = ! spectraProEnableDynamicLink;

		const newAttributes = {
			spectraProEnableDynamicLink: newValue,
		};

		if ( newValue ) {
			// If enabling and href is empty, set default dynamic href.
			if ( ! href ) {
				newAttributes.href = 'spectra-dynamic-link';
			}
		} else {
			// If disabling, remove dynamic href only if it was the placeholder.
			newAttributes.href = href === 'spectra-dynamic-link' ? '' : href;
		}

		setAttributes( newAttributes );
	};

	/**
	 * Handles keyboard events for interactive containers.
	 *
	 * @param {Object} event - The keyboard event.
	 */
	const handleKeyDown = ( event ) => {
		// Prevent event propagation for space and enter keys
		if ( event.key === ' ' || event.key === 'Enter' ) {
			event.stopPropagation();
		}
	};

	return (
		<PopoverCloseContext.Provider value={ onClose }>
			<div ref={ popoverRef }>
				<VStack spacing={ 4 }>
							{ /* Header with close button */ }
			<HStack justify="space-between">
				<strong>{ __( 'Dynamic Content', 'spectra-pro' ) }</strong>
				<Button
					icon="no-alt"
					label={ __( 'Close', 'spectra-pro' ) }
					onClick={ ( e ) => { e.stopPropagation(); onClose(); } }
					size="small"
					variant="tertiary"
				/>
			</HStack>

							{ /* Dynamic Image Toggle */ }
			<div 
				onClick={ ( e ) => e.stopPropagation() } 
				onKeyDown={ handleKeyDown }
				role="button"
				tabIndex={ 0 }
			>
				<ToggleControl
					label={ __( 'Dynamic Image', 'spectra-pro' ) }
					checked={ spectraProEnableDynamicImage }
					onChange={ handleImageToggle }
				/>
			</div>

				{ /* Dynamic Image Configuration */ }
				{ spectraProEnableDynamicImage && (
					<DynamicContentProvider>
						<DynamicImage
							type="image"
							blockName={ blockName }
							attributes={ attributes }
							setAttributes={ setAttributes }
						/>
					</DynamicContentProvider>
				) }

							{ /* Dynamic Link Toggle */ }
			<div 
				onClick={ ( e ) => e.stopPropagation() } 
				onKeyDown={ handleKeyDown }
				role="button"
				tabIndex={ 0 }
			>
				<ToggleControl
					label={ __( 'Dynamic Link', 'spectra-pro' ) }
					checked={ spectraProEnableDynamicLink }
					onChange={ handleLinkToggle }
				/>
			</div>

				{ /* Dynamic Link Configuration */ }
				{ spectraProEnableDynamicLink && (
					<DynamicContentProvider>
						<DynamicLink 
							attributes={ attributes } 
							setAttributes={ setAttributes } 
							type="image" 
						/>
					</DynamicContentProvider>
				) }
			</VStack>
			</div>
		</PopoverCloseContext.Provider>
	);
};

export default DynamicImageToolbarContent; 