import { useQueryClient } from '@tanstack/react-query';
import { useEffect, useRef } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { refreshLinkData } from '../shared/api/refreshLinkData';
import type { ScanState, Status } from '../shared/api/types/status';
import { formatNumber } from '../shared/lib/numbers';
import { useToast } from '../shared/ui/Toasts';

function scanFinishedText( status: Status ): string {
	return sprintf(
		/* translators: 1: number of links checked, 2: number of broken links */
		__(
			'Scan finished. %1$s links checked, %2$s broken.',
			'aiplaz-link-checkup'
		),
		formatNumber( status.counts.total ),
		formatNumber( status.counts.broken )
	);
}

export function useScanFinished( status: Status | undefined ): void {
	const queryClient = useQueryClient();
	const showToast = useToast();
	const previousState = useRef< ScanState | undefined >( undefined );
	const scanState = status?.scan.state;

	useEffect( () => {
		const hasFinished =
			previousState.current === 'running' && scanState === 'idle';

		if ( hasFinished && status !== undefined ) {
			refreshLinkData( queryClient );
			showToast( { text: scanFinishedText( status ) } );
		}

		previousState.current = scanState;
	}, [ queryClient, scanState, status, showToast ] );
}
