import { useEffect, useState } from '@wordpress/element';
import { refreshSettingsMeta, runLegacyAjax } from '../api';

function fmtUtc( ts ) {
	if ( ! ts ) {
		return '';
	}
	return new Date( ts * 1000 ).toISOString().slice( 0, 19 ).replace( 'T', ' ' ) + ' UTC';
}

function StatusLine( { label, children } ) {
	return (
		<p className="newsroom-settings__status-line">
			<strong>{ label }</strong> { children }
		</p>
	);
}

function IndexingTools( { meta, i18n, pro, setNotice, onMetaUpdate } ) {
	const ix = meta?.indexing || {};
	const gsc = meta?.gsc || {};
	const inow = meta?.indexnow || {};
	const [ jsonText, setJsonText ] = useState( '' );
	const [ showReplace, setShowReplace ] = useState( ! ix.jsonConfigured );
	const [ busy, setBusy ] = useState( '' );
	const [ toolMsg, setToolMsg ] = useState( '' );

	const bumpMeta = async () => {
		const next = await refreshSettingsMeta();
		onMetaUpdate( next );
		return next;
	};

	const runTool = async ( key, fn ) => {
		setBusy( key );
		setToolMsg( '' );
		try {
			const res = await fn();
			setToolMsg( res?.message || res?.message_human || '' );
			setNotice( { type: 'success', text: res?.message || res?.message_human || i18n?.saved } );
			await bumpMeta();
		} catch ( e ) {
			const msg = e?.message || i18n?.error;
			setToolMsg( msg );
			setNotice( { type: 'error', text: msg } );
		} finally {
			setBusy( '' );
		}
	};

	const saveJson = async ( clear = false ) => {
		setBusy( 'json' );
		setToolMsg( '' );
		try {
			const fields = {};
			if ( clear ) {
				fields.indexing_service_json_clear = '1';
			} else {
				fields.indexing_service_json = jsonText;
				if ( ix.jsonConfigured ) {
					fields.indexing_service_json_replace = '1';
				}
			}
			const res = await runLegacyAjax( 'newsai_save_indexing_sa', fields );
			setToolMsg( res.message || '' );
			setNotice( { type: 'success', text: res.message || i18n?.saved } );
			setJsonText( '' );
			setShowReplace( !! res.cleared );
			await bumpMeta();
		} catch ( e ) {
			setToolMsg( e.message );
			setNotice( { type: 'error', text: e.message } );
		} finally {
			setBusy( '' );
		}
	};

	const runBackfillSteps = async () => {
		const step = await runLegacyAjax( 'newsai_gsc_backfill_step' );
		const progress = step.progress || {};
		onMetaUpdate( {
			...meta,
			gsc: {
				...gsc,
				backfillRunning: ! step.done,
				backfillChunk: progress.chunk_index != null ? progress.chunk_index + 1 : gsc.backfillChunk,
				backfillTotal: progress.chunks ? progress.chunks.length : gsc.backfillTotal,
				backfillMessage: progress.last_message || '',
			},
		} );
		if ( step.done ) {
			await bumpMeta();
			return step;
		}
		await new Promise( ( r ) => setTimeout( r, 800 ) );
		return runBackfillSteps();
	};

	const startBackfill = async () => {
		setBusy( 'backfill' );
		try {
			await runLegacyAjax( 'newsai_gsc_backfill_start' );
			await runBackfillSteps();
			setNotice( { type: 'success', text: i18n?.saved } );
		} catch ( e ) {
			setNotice( { type: 'error', text: e.message } );
		} finally {
			setBusy( '' );
		}
	};

	useEffect( () => {
		if ( gsc.backfillRunning && ! busy ) {
			setBusy( 'backfill' );
			runBackfillSteps()
				.catch( () => {} )
				.finally( () => setBusy( '' ) );
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [] );

	const proDisabled = ! pro?.active;

	return (
		<div className="newsroom-settings__tools">
			<h5 className="newsroom-settings__tools-title">Google Indexing API</h5>
			{ ix.jsonLocked ? (
				<p className="description">{ i18n?.jsonLocked }</p>
			) : (
				<div className="newsroom-settings__json-panel">
					{ ix.jsonConfigured ? (
						<p className="newsroom-settings__chip-inline newsroom-settings__chip-inline--ok">{ i18n?.jsonConfigured }{ ix.clientEmail ? ` — ${ ix.clientEmail }` : '' }</p>
					) : (
						<p className="description">{ i18n?.jsonMissing }</p>
					) }
					{ ix.jsonConfigured && (
						<label className="newsroom-settings__checkbox-line">
							<input type="checkbox" checked={ showReplace } onChange={ ( e ) => setShowReplace( e.target.checked ) } disabled={ proDisabled } />
							{ i18n?.replaceJson }
						</label>
					) }
					{ ( showReplace || ! ix.jsonConfigured ) && (
						<textarea
							className="newsroom-settings__input newsroom-settings__textarea is-mono"
							rows={ 5 }
							value={ jsonText }
							disabled={ proDisabled || busy === 'json' }
							placeholder='{"type":"service_account",...}'
							onChange={ ( e ) => setJsonText( e.target.value ) }
						/>
					) }
					<div className="newsroom-settings__tool-row">
						<button type="button" className="button button-secondary" disabled={ proDisabled || busy === 'json' || ( ! ix.jsonConfigured && ! jsonText.trim() ) } onClick={ () => saveJson( false ) }>
							{ i18n?.saveJson }
						</button>
						{ ix.jsonConfigured && (
							<button type="button" className="button" disabled={ proDisabled || busy === 'json' } onClick={ () => saveJson( true ) }>
								{ i18n?.removeJson }
							</button>
						) }
						<button type="button" className="button" disabled={ proDisabled || !! busy } onClick={ () => runTool( 'indexing', () => runLegacyAjax( 'newsai_indexing_test' ) ) }>
							{ i18n?.testConnection }
						</button>
					</div>
				</div>
			) }
			<StatusLine label="Health:">{ ix.health }</StatusLine>
			{ ix.lastPing > 0 && <StatusLine label="Last ping:">{ fmtUtc( ix.lastPing ) }{ ix.lastCode ? ` · HTTP ${ ix.lastCode }` : '' }</StatusLine> }
			{ ix.lastError && <p className="newsroom-settings__status-error">{ ix.lastError }</p> }

			<h5 className="newsroom-settings__tools-title">Google Search Console</h5>
			{ gsc.lastSync ? (
				<StatusLine label="Last sync:">{ gsc.lastSync } UTC · { gsc.rows } rows</StatusLine>
			) : (
				<p className="description">No sync yet.</p>
			) }
			{ gsc.queryRows > 0 && <StatusLine label="Query table:">{ gsc.queryRows } rows</StatusLine> }
			{ gsc.lastError && <p className="newsroom-settings__status-error">{ gsc.lastError }</p> }
			<div className="newsroom-settings__tool-row">
				<button type="button" className="button" disabled={ proDisabled || !! busy } onClick={ () => runTool( 'gsc_test', () => runLegacyAjax( 'newsai_gsc_test' ) ) }>
					{ i18n?.testConnection }
				</button>
				<button type="button" className="button button-primary" disabled={ proDisabled || !! busy } onClick={ () => runTool( 'gsc_sync', () => runLegacyAjax( 'newsai_gsc_sync_now' ) ) }>
					{ i18n?.syncNow }
				</button>
				<button type="button" className="button" disabled={ proDisabled || !! busy || gsc.backfillRunning } onClick={ startBackfill }>
					{ gsc.backfillRunning ? i18n?.backfillRunning : i18n?.startBackfill }
				</button>
			</div>
			{ gsc.backfillRunning && gsc.backfillTotal > 0 && (
				<p className="description">Progress: month { gsc.backfillChunk } of { gsc.backfillTotal }{ gsc.backfillMessage ? ` · ${ gsc.backfillMessage }` : '' }</p>
			) }

			<h5 className="newsroom-settings__tools-title">IndexNow</h5>
			{ inow.key && (
				<p className="description">
					Key: <code>{ inow.key }</code>
					{ inow.keyUrl && <> · <a href={ inow.keyUrl } target="_blank" rel="noreferrer">verify file</a></> }
				</p>
			) }
			<StatusLine label="Health:">{ inow.health }</StatusLine>
			<button type="button" className="button" disabled={ proDisabled || !! busy } onClick={ () => runTool( 'indexnow', () => runLegacyAjax( 'newsai_indexnow_test' ) ) }>
				{ i18n?.testIndexNow }
			</button>

			{ toolMsg && <p className="newsroom-settings__tool-msg">{ toolMsg }</p> }
		</div>
	);
}

function WeeklyReportTools( { meta, i18n, setNotice, onMetaUpdate } ) {
	const wr = meta?.weeklyReport || {};
	const [ busy, setBusy ] = useState( false );

	return (
		<div className="newsroom-settings__tools">
			{ wr.lastSent > 0 && (
				<StatusLine label="Last sent:">{ fmtUtc( wr.lastSent ) } · { wr.lastCount } recipient(s)</StatusLine>
			) }
			<button
				type="button"
				className="button"
				disabled={ busy }
				onClick={ async () => {
					setBusy( true );
					try {
						const res = await runLegacyAjax( 'newsai_weekly_report_test' );
						setNotice( { type: 'success', text: res.message_human || res.message || i18n?.saved } );
						const next = await refreshSettingsMeta();
						onMetaUpdate( next );
					} catch ( e ) {
						setNotice( { type: 'error', text: e.message } );
					} finally {
						setBusy( false );
					}
				} }
			>
				{ i18n?.testWeeklyReport }
			</button>
		</div>
	);
}

export function SectionTools( { section, meta, i18n, pro, setNotice, onMetaUpdate } ) {
	if ( ! section?.tools?.length ) {
		return null;
	}
	return (
		<>
			{ section.tools.includes( 'indexing_full' ) && (
				<IndexingTools meta={ meta } i18n={ i18n } pro={ pro } setNotice={ setNotice } onMetaUpdate={ onMetaUpdate } />
			) }
			{ section.tools.includes( 'weekly_report' ) && (
				<WeeklyReportTools meta={ meta } i18n={ i18n } setNotice={ setNotice } onMetaUpdate={ onMetaUpdate } />
			) }
		</>
	);
}
