/**
 * WordPress dependencies
 */
import { Button, Modal } from '@safe-wordpress/components';
import { createInterpolateElement, useState } from '@safe-wordpress/element';
import { _x } from '@safe-wordpress/i18n';
import { addQueryArgs } from '@safe-wordpress/url';

/**
 * External dependencies
 */
import { usePluginSetting } from '@nab/data';

/**
 * Internal dependencies
 */
import './style.scss';
import { ClipboardButton } from '../clipboard-button';

export function PreviewUrlButton(): JSX.Element | null {
	const isDebuggingEnabled = usePluginSetting( 'isDebuggingEnabled' );
	const hasRunningExperiments = usePluginSetting( 'hasRunningExperiments' );
	const homeUrl = usePluginSetting( 'homeUrl' );
	const [ isModalVisible, showModal ] = useState( false );

	if ( ! isDebuggingEnabled || ! hasRunningExperiments ) {
		return null;
	}

	const testUrl = addQueryArgs( homeUrl, { nabstaging: '1' } );
	return (
		<>
			<Button
				className="page-title-action nab-preview-url-title-action"
				onClick={ () => showModal( true ) }
			>
				{ _x( 'Preview', 'command', 'nelio-ab-testing' ) }
			</Button>
			{ isModalVisible && (
				<Modal
					className="nab-preview-url-modal"
					title={ _x(
						'How to Preview Running Tests',
						'text',
						'nelio-ab-testing'
					) }
					isDismissible
					shouldCloseOnEsc
					shouldCloseOnClickOutside
					onRequestClose={ () => showModal( false ) }
				>
					<p>
						{ createInterpolateElement(
							_x(
								'Copy this URL and open it in an <strong>incognito window</strong> to preview active tests:',
								'user',
								'nelio-ab-testing'
							),
							{ strong: <strong /> }
						) }
					</p>
					<div className="nab-preview-url-modal__url">
						<input type="text" value={ testUrl } readOnly />
						<ClipboardButton text={ testUrl } />
					</div>
				</Modal>
			) }
		</>
	);
}
