/**
 * WordPress dependencies
 */
import { useDispatch } from '@safe-wordpress/data';
import { _x } from '@safe-wordpress/i18n';

/**
 * External dependencies
 */
import { ConfirmationDialog } from '@nab/components';
import { store as NAB_DATA, usePageAttribute } from '@nab/data';

export function AlternativeApplicationModal(): JSX.Element | null {
	const [ alternativeToApply, setAlternativeToApply ] = usePageAttribute(
		'results/alternativeToApply',
		false
	);
	const [ alternativeBeingApplied ] = usePageAttribute(
		'results/alternativeBeingApplied',
		false
	);

	const { applyAlternative } = useDispatch( NAB_DATA );
	const closeModal = () => setAlternativeToApply( false );

	if ( ! alternativeToApply ) {
		return null;
	}

	return (
		<ConfirmationDialog
			title={ _x( 'Apply Variant', 'text', 'nelio-ab-testing' ) }
			text={ _x(
				'You’re about to overwrite the tested element with this variant. This operation can’t be undone. Are you sure you want to continue?',
				'user',
				'nelio-ab-testing'
			) }
			confirmLabel={
				alternativeBeingApplied
					? _x(
							'Applying Variant…',
							'text (an alternative)',
							'nelio-ab-testing'
					  )
					: _x( 'Apply Variant', 'command', 'nelio-ab-testing' )
			}
			isConfirmBusy={ !! alternativeBeingApplied }
			isConfirmEnabled={ ! alternativeBeingApplied }
			isCancelEnabled={ ! alternativeBeingApplied }
			isOpen={ !! alternativeToApply }
			onCancel={ closeModal }
			onConfirm={ () => {
				void applyAlternative( alternativeToApply ).then( () =>
					closeModal()
				);
			} }
		/>
	);
}
