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

/**
 * Internal dependencies.
 */
import { DynamicContentProvider } from '@spectra-pro-extensions/dynamic-content//context/DynamicContentContext';
import DynamicLink from '@spectra-pro-extensions/dynamic-content/components/DynamicLink';

/**
 * Extends the WordPress Link Control with dynamic link controls.
 *
 * Adds a toggle to enable/disable dynamic link support and renders a dynamic link
 * configuration panel when enabled. Updates block attributes to reflect the dynamic
 * link state.
 *
 * @since x.x.x
 *
 * @param {Object}   defaultValue        - The default value returned by the Link Control.
 * @param {Object}   props               - The component props.
 * @param {Object}   props.attributes    - The block's attributes.
 * @param {Function} props.setAttributes - Function to update block attributes.
 * @return {Element} The enhanced Link Control with dynamic link controls.
 */
const LinkControlWithDynamicLink = ( defaultValue, props ) => {
	// Destructure only what we need from props
	const { attributes, setAttributes } = props;

	// Defensive check for attributes
	if ( ! attributes ) {
		return defaultValue;
	}

	const { spectraProEnableDynamicLink = false } = attributes;

	/**
	 * Handles toggling the dynamic link feature.
	 *
	 * Updates the block's attributes to enable or disable dynamic link support.
	 */
	const handleToggle = () => {
		setAttributes( {
			spectraProEnableDynamicLink: ! spectraProEnableDynamicLink,
		} );
	};

	return (
		<VStack className="spectra-pro-block-editor-link-control">
			<ToggleControl
				label={ __( 'Dynamic Link', 'spectra-pro' ) }
				checked={ spectraProEnableDynamicLink }
				onChange={ handleToggle }
			/>
			{ spectraProEnableDynamicLink && (
				<DynamicContentProvider>
					<DynamicLink attributes={ attributes } setAttributes={ setAttributes } />
				</DynamicContentProvider>
			) }
		</VStack>
	);
};

export default LinkControlWithDynamicLink;
