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

/**
 * External dependencies
 */
import { store as NAB_DATA } from '@nab/data';

/**
 * Internal dependencies
 */
import './style.scss';
import { RunningExperiment } from './running-experiment';

type RunningExperimentsProps = {
	readonly onExtendedClicked: () => void;
};

export function RunningExperiments( {
	onExtendedClicked,
}: RunningExperimentsProps ): JSX.Element {
	const { allRunningUrl, experiments, isLoading, runningCount } = useSelect(
		( select ) => ( {
			allRunningUrl: select( NAB_DATA ).getAdminUrl(
				'edit.php?post_type=nab_experiment&post_status=nab_running&order=desc'
			),
			experiments: select( NAB_DATA ).getRunningExperimentSummaries(),
			isLoading: select( NAB_DATA ).getRunningExperimentSummaries().length
				? false
				: ! select( NAB_DATA ).isRecommendationEngineDataLoaded(),
			runningCount: select( NAB_DATA ).getRunningExperimentCount(),
		} ),
		[]
	);

	if ( ! experiments.length || isLoading ) {
		return (
			<section className="nab-running-tests nab-overview-card">
				<div className="nab-running-tests__header">
					<h2 className="nab-running-tests__title">
						{ _x( 'Running tests', 'text', 'nelio-ab-testing' ) }
					</h2>
				</div>

				<div className="nab-running-tests__empty">
					<div
						className="nab-running-tests__empty-graphic"
						aria-hidden="true"
					>
						🧪
					</div>
					<h3 className="nab-running-tests__empty-title">
						{ isLoading
							? _x( 'Loading…', 'text', 'nelio-ab-testing' )
							: _x(
									'No tests running yet',
									'text',
									'nelio-ab-testing'
							  ) }
					</h3>
					{ ! isLoading && (
						<p className="nab-running-tests__empty-text">
							{ _x(
								'Launch a test to start collecting insights.',
								'user',
								'nelio-ab-testing'
							) }
						</p>
					) }
				</div>
			</section>
		);
	}

	return (
		<section className="nab-running-tests nab-overview-card">
			<div className="nab-running-tests__header">
				<h2 className="nab-running-tests__title">
					{ _x( 'Running tests', 'text', 'nelio-ab-testing' ) }
					<span className="nab-running-tests__count">
						{ runningCount }
					</span>
				</h2>

				<Button
					variant="link"
					className="nab-running-tests__link"
					onClick={ onExtendedClicked }
				>
					{ _x( 'Extended view →', 'text', 'nelio-ab-testing' ) }
				</Button>
			</div>

			<ul className="nab-running-tests__list">
				{ experiments.map( ( experiment ) => (
					<RunningExperiment
						key={ experiment.id }
						experiment={ experiment }
					/>
				) ) }
			</ul>

			<Button
				variant="link"
				className="nab-running-tests__footer-link"
				href={ allRunningUrl }
			>
				{ _x( 'All running tests →', 'text', 'nelio-ab-testing' ) }
			</Button>
		</section>
	);
}
