/**
 * WordPress dependencies
 */
import { CheckboxControl } from '@safe-wordpress/components';
import { useDispatch } from '@safe-wordpress/data';
import { _x } from '@safe-wordpress/i18n';

/**
 * External dependencies
 */
import { createScopeRule } from '@nab/utils';
import type { ScopeRule } from '@nab/types';

/**
 * Internal dependencies
 */
import { store as NAB_EDITOR } from '../../../store';

export type ConsistencyScopeProps = {
	readonly rules: ReadonlyArray< ScopeRule >;
};

export const ConsistencyScope = ( {
	rules,
}: ConsistencyScopeProps ): JSX.Element => {
	const enableConsistency = useConsistencyEnabler();
	return (
		<CheckboxControl
			label={ _x( 'Global Consistency', 'command', 'nelio-ab-testing' ) }
			checked={ ! rules.length }
			onChange={ () => enableConsistency( ! rules.length ) }
			help={
				! rules.length
					? _x(
							'Variants will be visible on the tested element’s page. All other pages will also show the appropriate variant of this test whenever the tested element appears on them.',
							'text',
							'nelio-ab-testing'
					  )
					: _x(
							'Variants will be visible only on the tested element’s page.',
							'text',
							'nelio-ab-testing'
					  )
			}
		/>
	);
};

// =====
// HOOKS
// =====

const useConsistencyEnabler = () => {
	const { setScopeRules } = useDispatch( NAB_EDITOR );
	return ( consistency: boolean ) =>
		setScopeRules(
			consistency ? [ createScopeRule( { type: 'tested-post' } ) ] : []
		);
};
