/**
 * 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 ProductConsistencyScopeProps = {
	readonly rules: ReadonlyArray< ScopeRule >;
};

export const ProductConsistencyScope = ( {
	rules,
}: ProductConsistencyScopeProps ): JSX.Element => {
	const enableConsistency = useConsistencyEnabler();
	return (
		<CheckboxControl
			label={ _x( 'Product’s page only', 'command', 'nelio-ab-testing' ) }
			checked={ rules.length }
			onChange={ () => enableConsistency( ! rules.length ) }
			help={
				! rules.length
					? _x(
							'Variants will be visible everywhere on your store: the product’s page, shopping carts, the checkout page, on a “related products” section, etc.',
							'text',
							'nelio-ab-testing'
					  )
					: _x(
							'Variants will be visible only on the tested product’s page.',
							'text',
							'nelio-ab-testing'
					  ) +
					  ' ' +
					  _x(
							'Moreover, price testing is disabled.',
							'user',
							'nelio-ab-testing'
					  )
			}
		/>
	);
};

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

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