import { useEffect, useState } from '@wordpress/element';
import { __, _n, sprintf } from '@wordpress/i18n';
import { useNotices } from '../../contexts/NoticesContext';
import { backfill, fetchSyncStatus, syncNow } from './api';

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

/**
 * Last sync result plus "Sync now" and "Backfill" (WordPress method), or the status the
 * sheet reports (Apps Script method). Uses the saved settings, not unsaved edits.
 */
export default function SyncStatus( { method, canRun } ) {
	const notices = useNotices();
	const [ sync, setSync ] = useState( null );
	const [ busy, setBusy ] = useState( '' );
	const isWordPress = method === 'cron';

	const refresh = () => fetchSyncStatus().then( ( data ) => setSync( data.sync ) ).catch( () => {} );

	useEffect( () => {
		refresh();
	}, [ method ] );

	// After saving (a report filter change queues a rebuild) and while a rebuild runs, read the status again.
	useEffect( () => {
		window.addEventListener( 'ssgsw-analytics-saved', refresh );
		return () => window.removeEventListener( 'ssgsw-analytics-saved', refresh );
	}, [] );
	const rebuildStatus = sync && sync.rebuild ? sync.rebuild.status : '';
	useEffect( () => {
		if ( rebuildStatus !== 'queued' && rebuildStatus !== 'running' ) {
			return undefined;
		}
		const timer = window.setInterval( refresh, 15000 );
		return () => window.clearInterval( timer );
	}, [ rebuildStatus ] );

	const run = async ( key, fn, okTitle ) => {
		setBusy( key );
		try {
			const data = await fn();
			setSync( data.sync );
			notices.success( okTitle, data.message );
		} catch ( error ) {
			notices.error( __( 'The update did not work', TEXT_DOMAIN ), error.message );
			fetchSyncStatus().then( ( data ) => setSync( data.sync ) ).catch( () => {} );
		} finally {
			setBusy( '' );
		}
	};

	const last = sync && sync.last_sync;
	const apps = sync && sync.apps_script;
	const rebuild = sync && sync.rebuild;
	const rebuildText = () => {
		if ( ! rebuild ) {
			return '';
		}
		switch ( rebuild.status ) {
			case 'queued':
				return __( 'Report tabs: the new filters were saved; rebuilding the tabs starts in about 30 seconds.', TEXT_DOMAIN );
			case 'running':
				return sprintf(
					/* translators: 1: days written, 2: days in total */
					__( 'Report tabs: rebuilding with the new filters, %1$d of %2$d days written.', TEXT_DOMAIN ),
					Number( rebuild.done_days || 0 ),
					Number( rebuild.total_days || 0 )
				);
			case 'done':
				return sprintf( /* translators: 1: date and time, 2: details */ __( 'Report tabs rebuilt with the new filters on %1$s. %2$s', TEXT_DOMAIN ), rebuild.finished_at || '', rebuild.message || '' );
			case 'sheet':
				return __( 'Report tabs: the new filters were saved. The sheet applies them on its next sync.', TEXT_DOMAIN );
			default:
				return rebuild.message || '';
		}
	};

	return (
		<div className="ssgsw-analytics-section">
			<h3 className="ssgsw-analytics-section__title">{ __( 'Update status', TEXT_DOMAIN ) }</h3>
			<div className="ssgsw-analytics-panel">
				{ isWordPress ? (
					<>
						<p className="ssgsw-analytics-panel__intro">
							{ last
								? sprintf(
									/* translators: 1: date and time, 2: result */
									__( 'Last update: %1$s (%2$s).', TEXT_DOMAIN ),
									last.time,
									last.status === 'ok' ? last.message : last.message || __( 'failed', TEXT_DOMAIN )
								)
								: __( 'The sheet has not been updated yet.', TEXT_DOMAIN ) }
						</p>
						{ last && last.status === 'error' && (
							<p className="ssgsw-analytics-warning">{ last.message }</p>
						) }
						{ rebuild && rebuild.status && rebuild.status !== 'error' && rebuild.status !== 'sheet' && (
						<p className="ssgsw-analytics-panel__note">{ rebuildText() }</p>
					) }
					{ rebuild && rebuild.status === 'error' && (
						<p className="ssgsw-analytics-warning">{ sprintf( __( 'Rebuilding the report tabs failed: %s It is retried automatically.', TEXT_DOMAIN ), rebuild.message || '' ) }</p>
					) }
					{ sync && sync.next_run && (
							<p className="ssgsw-analytics-panel__note">{ sprintf( __( 'Next update: %s (store time).', TEXT_DOMAIN ), sync.next_run ) }</p>
						) }
						{ ! canRun && (
							<p className="ssgsw-analytics-panel__note">{ __( 'Turn on Sales Analytics and automatic updates, then save, to use these buttons.', TEXT_DOMAIN ) }</p>
						) }
						<div className="ssgsw-analytics-actions">
							<button type="button" className="ssgsw-analytics-btn ssgsw-analytics-btn--primary" disabled={ ! canRun || !! busy || ( sync && sync.running ) } aria-busy={ busy === 'now' } onClick={ () => run( 'now', syncNow, __( 'Sheet updated', TEXT_DOMAIN ) ) }>
								{ busy === 'now' ? __( 'Updating…', TEXT_DOMAIN ) : __( 'Update the sheet now', TEXT_DOMAIN ) }
							</button>
							{ [ 30, 90, 365 ].map( ( days ) => (
								<button key={ days } type="button" className="ssgsw-analytics-btn ssgsw-analytics-btn--secondary" disabled={ ! canRun || !! busy || ( sync && sync.running ) } aria-busy={ busy === 'b' + days } onClick={ () => run( 'b' + days, () => backfill( days ), __( 'Past sales added', TEXT_DOMAIN ) ) }>
									{ busy === 'b' + days ? __( 'Adding…', TEXT_DOMAIN ) : sprintf( __( 'Add past sales (%d days)', TEXT_DOMAIN ), days ) }
								</button>
							) ) }
						</div>
					</>
				) : (
					<>
						{ apps ? (
							<p className="ssgsw-analytics-panel__intro">
								{ apps.trigger_installed ? __( 'The Google Sheets timer is on.', TEXT_DOMAIN ) : __( 'The Google Sheets timer is not on yet.', TEXT_DOMAIN ) }{ ' ' }
								{ apps.last_run ? sprintf( _n( 'Last run in the sheet: %1$s (%2$d row).', 'Last run in the sheet: %1$s (%2$d rows).', Number( apps.rows ) || 0, TEXT_DOMAIN ), apps.last_run, apps.rows ) : '' }
							</p>
						) : (
							<p className="ssgsw-analytics-panel__intro">{ __( 'The sheet has not reported yet. Open it and turn on the timer (steps above).', TEXT_DOMAIN ) }</p>
						) }
						{ apps && apps.error && <p className="ssgsw-analytics-warning">{ apps.error }</p> }
						{ rebuild && rebuild.status === 'sheet' && <p className="ssgsw-analytics-panel__note">{ rebuildText() }</p> }
					</>
				) }
			</div>
		</div>
	);
}
