import { useEffect, useRef, useState } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { ajaxPost } from '../../api/ajax';
import { useNotices } from '../../contexts/NoticesContext';
import { getPublicUrl, isWooInstalled } from '../../Helpers';

const TEXT_DOMAIN = 'stock-sync-with-google-sheet-for-woocommerce';

/**
 * Blocking prompt shown while WooCommerce is missing (port of the removed templates/setup/woocommerce.php).
 * Installs and/or activates WooCommerce through the existing ssgsw_activate_woocommerce action.
 *
 * @param {Object}   props
 * @param {Function} props.onActivated Called once WooCommerce is active.
 */
const WooCommercePrompt = ( { onActivated } ) => {
	const notices = useNotices();
	const [ installed ] = useState( isWooInstalled() );
	const [ activating, setActivating ] = useState( false );
	const buttonRef = useRef( null );

	useEffect( () => {
		buttonRef.current?.focus();
	}, [] );

	const activate = async () => {
		if ( activating ) {
			return;
		}
		setActivating( true );

		try {
			const response = await ajaxPost( 'ssgsw_activate_woocommerce' );
			if ( response.success ) {
				onActivated();
				return;
			}
			notices.error(
				sprintf(
					/* translators: %s: error message. */
					__( 'FlexStock: %s', TEXT_DOMAIN ),
					response.message || __( 'Something went wrong', TEXT_DOMAIN )
				)
			);
		} catch ( error ) {
			notices.error( __( 'FlexStock: Something went wrong', TEXT_DOMAIN ) );
		} finally {
			setActivating( false );
		}
	};

	const title = `${ installed ? __( 'Activate', TEXT_DOMAIN ) : __( 'Install and activate', TEXT_DOMAIN ) } WooCommerce`;

	return (
		<div className="ssgs-popup bg-none ssgsw-woo-prompt">
			<div className="popup-overlay"></div>
			<div className="content text-center" role="dialog" aria-modal="true" aria-labelledby="ssgsw-woo-title">
				<figure className="media">
					<img src={ `${ getPublicUrl() }images/woo.svg` } alt="" />
				</figure>

				{ activating ? (
					<div className="ssgsw_flex_loader" role="status">
						<span className="ssgsw-spinner ssgsw-spinner--lg" aria-hidden="true"></span>
						{ __( 'Activating WooCommerce...', TEXT_DOMAIN ) }
						<br />
						{ __( 'This may take a couple of seconds.', TEXT_DOMAIN ) }
					</div>
				) : (
					<>
						<h3 className="title" id="ssgsw-woo-title">
							{ title }
						</h3>
						<div className="text">
							<p>
								{ __( 'The plugin only works when WooCommerce is', TEXT_DOMAIN ) }{ ' ' }
								{ ! installed && <strong>{ __( 'installed and', TEXT_DOMAIN ) } </strong> }
								<strong>{ __( 'activated', TEXT_DOMAIN ) }</strong>
							</p>
						</div>
						<button ref={ buttonRef } type="button" onClick={ activate } className="ssgs-btn flex-button">
							{ installed ? __( 'Activate', TEXT_DOMAIN ) : __( 'Install & activate', TEXT_DOMAIN ) }
						</button>
					</>
				) }
			</div>
		</div>
	);
};

export default WooCommercePrompt;
