import { useState } from '@wordpress/element';
import type { Problem } from '../../shared/links/problem';
import {
	emptyAddressState,
	initialTestState,
	testStateOf,
	UNTESTED,
	type AddressTestState,
} from './addressTest';
import { useTestAddress } from './linkDetailQueries';

export function useAddressTest( problem: Problem ) {
	const testAddress = useTestAddress();
	const [ testState, setTestState ] = useState< AddressTestState >( () =>
		initialTestState( problem )
	);

	const runTest = ( typedAddress: string ) => {
		const address = typedAddress.trim();

		if ( address === '' ) {
			setTestState( emptyAddressState() );

			return;
		}

		setTestState( { kind: 'checking' } );
		testAddress.mutate( address, {
			onSuccess: ( checkResult ) => {
				setTestState( testStateOf( checkResult ) );
			},
			onError: ( error ) => {
				setTestState( { kind: 'bad', text: error.message } );
			},
		} );
	};

	const forgetTest = () => {
		setTestState( UNTESTED );
	};

	return { testState, runTest, forgetTest };
}

export type AddressTest = ReturnType< typeof useAddressTest >;
