import { useState } from '@wordpress/element';
import { runSettingsAction } from '../api';

export function SectionActions( { actions, meta, i18n, setNotice, onActionDone } ) {
	const [ busy, setBusy ] = useState( false );
	if ( ! actions || ! actions.length ) {
		return null;
	}

	const warm = async () => {
		setBusy( true );
		setNotice( null );
		try {
			const res = await runSettingsAction( 'schema_warm_batch', {} );
			setNotice( { type: 'success', text: res.message || i18n?.saved } );
			if ( onActionDone ) {
				onActionDone( res );
			}
		} catch ( e ) {
			setNotice( { type: 'error', text: e?.message || i18n?.error } );
		} finally {
			setBusy( false );
		}
	};

	return (
		<div className="newsroom-settings__actions">
			{ actions.includes( 'schema_warm_batch' ) && (
				<div className="newsroom-settings__action-row">
					<button type="button" className="button" disabled={ busy } onClick={ warm }>
						{ i18n?.warmSchema }
					</button>
					{ meta?.schemaWarm?.last > 0 && (
						<p className="description">
							{ `Last batch: ${ new Date( meta.schemaWarm.last * 1000 ).toISOString().slice( 0, 16 ).replace( 'T', ' ' ) } UTC — ${ meta.schemaWarm.count } post(s).` }
						</p>
					) }
				</div>
			) }
		</div>
	);
}
