/**
 * External dependencies.
 */
import { BlockControls } from '@wordpress/block-editor';
import { ToolbarGroup, ToolbarButton, Popover } from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import { useState, useRef, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies.
 */
import DynamicImageToolbarContent from '@spectra-pro-extensions/dynamic-content/components/DynamicImageToolbarContent';
import blockIcons from '@spectra-pro-helpers/block-icons';

/**
 * Renders a toolbar button to toggle the dynamic image configuration popover.
 *
 * Displays a button in the block editor toolbar for core/image blocks, which opens a
 * popover for configuring dynamic image and link settings. The button is only shown 
 * for core/image blocks and manages the visibility of the popover.
 *
 * @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.
 * @return {Element|null} The toolbar button and popover, or null if not a core/image block.
 */
const DynamicImageButton = ( props ) => {
	const { blockName, attributes, setAttributes } = props;

	// State to manage popover visibility.
	const [ isPopoverVisible, setIsPopoverVisible ] = useState( false );
	
	// Ref for the popover container to prevent unwanted closing.
	const popoverRef = useRef( null );
	
	// Add global click listener to handle outside clicks manually.
	useEffect( () => {
		if ( ! isPopoverVisible ) return;
		
		const handleGlobalClick = ( event ) => {
			// Check if click is outside our components.
			const isWithinPopover = popoverRef.current?.contains( event.target );
			const isToolbarButton = event.target?.closest( '[aria-label="Dynamic Content"]' );
						
			if ( ! isWithinPopover && ! isToolbarButton ) {
				setIsPopoverVisible( false );
			}
		};
		
		// Add listener with a small delay to avoid immediate triggering
		setTimeout( () => {
			document.addEventListener( 'click', handleGlobalClick, true );
		}, 100 );
		
		return () => {
			document.removeEventListener( 'click', handleGlobalClick, true );
		};
	}, [ isPopoverVisible ] );

	// Get the currently selected block from the block editor.
	const selectedBlock = useSelect( ( select ) => select( 'core/block-editor' ).getSelectedBlock(), [] );

	// Only show for core/image blocks
	if ( ! selectedBlock || selectedBlock.name !== 'core/image' ) {
		return null;
	}

	const {
		spectraProEnableDynamicImage,
		spectraProEnableDynamicLink,
	} = attributes;

	// Determine if any dynamic feature is active
	const isActive = spectraProEnableDynamicImage || spectraProEnableDynamicLink;

	/**
	 * Closes the popover.
	 */
	const onClose = () => setIsPopoverVisible( false );

	/**
	 * Reopens the popover.
	 */
	const onReopen = () => setIsPopoverVisible( true );

	/**
	 * Enhanced close function that includes reopen capability.
	 */
	const closeWithReopen = Object.assign( onClose, { reopen: onReopen } );

	/**
	 * Toggles the visibility of the popover.
	 */
	const onToggle = () => setIsPopoverVisible( ! isPopoverVisible );

	return (
		<BlockControls>
			<ToolbarGroup>
				{ /* Toolbar button to toggle the dynamic image popover */ }
				<ToolbarButton
					icon={ blockIcons.dynamic_content }
					label={ __( 'Dynamic Content', 'spectra-pro' ) }
					onClick={ onToggle }
					isActive={ isActive }
				/>
			</ToolbarGroup>
			{ /* Show popover when explicitly toggled */ }
			{ isPopoverVisible && (
				<Popover
					focusOnMount={ false }
					className="spectra-pro-dynamic-image-popover"
					onClickOutside={ () => {} }
					onFocusOutside={ () => {} }
					position="bottom left"
					noArrow={ false }
				>
					<DynamicImageToolbarContent 
						blockName={ blockName }
						attributes={ attributes }
						setAttributes={ setAttributes }
						onClose={ closeWithReopen }
						popoverRef={ popoverRef }
					/>
				</Popover>
			) }
		</BlockControls>
	);
};

export default DynamicImageButton; 