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

/**
 * External dependencies
 */
import type { CustomUrlScopeRule, ScopeRule, ScopeType } from '@nab/types';

/**
 * Internal dependencies
 */
import { getScopeExplanation } from './explanation';
import { useExperimentAttribute } from '../../hooks';

export type CustomUrlScopeProps = {
	readonly scopeSupport: ScopeType;
};

export const CustomUrlScope = ( {
	scopeSupport,
}: CustomUrlScopeProps ): JSX.Element => {
	const rules = useExperimentAttribute( 'scope' ) || [];
	const status = useExperimentAttribute( 'status' ) ?? 'running';

	if ( ! rules.length ) {
		return <p>{ getScopeExplanation( scopeSupport, rules, status ) }</p>;
	}

	return (
		<>
			<p>{ getScopeExplanation( scopeSupport, rules, status ) }</p>

			<ul className="nab-experiment-scope__rule-list">
				{ rules
					.filter( isCustomUrlScopeRule )
					.map( ( { id, attributes: { value, type } } ) => (
						<li
							key={ id }
							className="nab-experiment-scope__rule-list-item"
						>
							<span className="nab-experiment-scope__active-rule-type">
								{ getLabel( type ) }
							</span>
							<input
								type="text"
								className="nab-experiment-scope__active-rule-value"
								value={ value }
								readOnly
							/>
						</li>
					) ) }
			</ul>
		</>
	);
};

// =======
// HELPERS
// =======

const isCustomUrlScopeRule = ( r: ScopeRule ): r is CustomUrlScopeRule =>
	'tested-post' !== r.attributes.type;

function getLabel(
	type: CustomUrlScopeRule[ 'attributes' ][ 'type' ]
): string {
	switch ( type ) {
		case 'exact':
			return _x( 'URL is:', 'text', 'nelio-ab-testing' );
		case 'partial':
			return _x( 'URL contains:', 'text', 'nelio-ab-testing' );
		case 'different':
			return _x( 'URL is not:', 'text', 'nelio-ab-testing' );
		case 'partial-not-included':
			return _x( 'URL does not contain:', 'text', 'nelio-ab-testing' );
	}
}
