import { useCallback, useEffect, useState } from '@wordpress/element';
import { loadProPayload, markReactAdminReady, runProLicenseAction } from './api';
import { LoadingState } from './components/LoadingState';

export default function ProApp() {
	const [ payload, setPayload ] = useState( null );
	const [ loading, setLoading ] = useState( true );
	const [ notice, setNotice ] = useState( null );
	const [ key, setKey ] = useState( '' );
	const [ email, setEmail ] = useState( '' );
	const [ busy, setBusy ] = useState( false );
	const [ loadError, setLoadError ] = useState( '' );

	const load = useCallback( async () => {
		setLoading( true );
		setLoadError( '' );
		try {
			const data = await loadProPayload();
			setPayload( data );
			setEmail( data.email || '' );
		} catch ( e ) {
			setLoadError( e && e.message ? String( e.message ) : 'load_failed' );
		} finally {
			markReactAdminReady();
			setLoading( false );
		}
	}, [] );

	useEffect( () => { load(); }, [ load ] );

	const i18n = payload?.i18n || {};
	if ( loading ) {
		return <LoadingState label={ i18n.loading || 'Loading…' } />;
	}
	if ( ! payload ) {
		return (
			<div className="nros-page nros-page--pro">
				<div className="nros-page-error">
					<h2>{ i18n.error || 'PRO license could not load.' }</h2>
					{ loadError && <p><code>{ loadError }</code></p> }
					<button type="button" className="button button-primary" onClick={ load }>Retry</button>
				</div>
			</div>
		);
	}

	const runAction = async ( action ) => {
		if ( action === 'deactivate' && ! window.confirm( i18n.confirm_deact ) ) {
			return;
		}
		setBusy( true );
		setNotice( null );
		try {
			const res = await runProLicenseAction( action, { key, email }, payload.licenseNonce );
			if ( res.payload ) {
				setPayload( res.payload );
			}
			setNotice( { type: 'success', text: res.message || i18n.refreshed } );
		} catch ( e ) {
			setNotice( { type: 'error', text: e?.message || i18n.error } );
		} finally {
			setBusy( false );
		}
	};

	return (
		<div className="nros-page nros-page--pro">
			<header className="nros-page__head">
				<div>
					<h1 className="nros-page__title">{ i18n.title }</h1>
					<p className="nros-page__sub">{ i18n.subtitle }</p>
				</div>
			</header>

			{ notice && (
				<div className={ `nros-notice nros-notice--${ notice.type }` }>{ notice.text }</div>
			) }

			<div className="nros-bento-card nros-pro-card">
				{ payload.isDevBuild && <p className="nros-pro-dev">{ i18n.dev_build }</p> }

				<div className="nros-pro-status">
					<span className="nros-pro-status__label">{ i18n.status }</span>
					<span className={ `nros-pro-pill${ payload.valid ? ' is-active' : '' }` }>
						{ payload.valid ? i18n.valid : ( payload.expired ? i18n.expired : i18n.inactive ) }
					</span>
				</div>

				{ payload.maskedKey && (
					<p><strong>{ i18n.key }:</strong> <code>{ payload.maskedKey }</code></p>
				) }
				{ payload.expiresAt && (
					<p><strong>{ i18n.paid_through }:</strong> { payload.expiresAt }</p>
				) }
				<p><strong>{ i18n.site }:</strong> <code>{ payload.siteUrl }</code></p>

				{ payload.canManage && ! payload.valid && (
					<form className="nros-pro-form" onSubmit={ ( e ) => { e.preventDefault(); runAction( 'activate' ); } }>
						<label>
							<span>{ i18n.key }</span>
							<input type="text" value={ key } onChange={ ( e ) => setKey( e.target.value ) } placeholder="NROS-XXXX-XXXX-XXXX" required />
							<small>{ i18n.key_hint }</small>
						</label>
						<label>
							<span>{ i18n.email }</span>
							<input type="email" value={ email } onChange={ ( e ) => setEmail( e.target.value ) } required />
						</label>
						<button type="submit" className="button button-primary" disabled={ busy }>{ i18n.activate }</button>
					</form>
				) }

				{ payload.canManage && payload.valid && (
					<div className="nros-pro-actions">
						<button type="button" className="button" disabled={ busy } onClick={ () => runAction( 'refresh' ) }>{ i18n.refresh }</button>
						<button type="button" className="button button-secondary" disabled={ busy } onClick={ () => runAction( 'deactivate' ) }>{ i18n.deactivate }</button>
					</div>
				) }

				{ ! payload.canManage && <p>{ i18n.no_access }</p> }

				<p className="nros-pro-buy">
					<a href={ payload.buyUrl } className="button" target="_blank" rel="noopener noreferrer">{ i18n.buy }</a>
				</p>

				{ ( payload.features || [] ).length > 0 && (
					<div className="nros-pro-features">
						<h3>{ i18n.features }</h3>
						<ul>
							{ payload.features.map( ( f, i ) => <li key={ i }>{ f }</li> ) }
						</ul>
					</div>
				) }
			</div>
		</div>
	);
}
