/**
 * 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 { PendingExperiment } from './pending-experiment';

export function PendingExperiments(): JSX.Element {
	const { allPendingUrl, experiments, isLoading, pendingCount } = useSelect(
		( select ) => ( {
			allPendingUrl: select( NAB_DATA ).getAdminUrl(
				'edit.php?post_type=nab_experiment&post_status=draft,nab_ready'
			),
			experiments: select( NAB_DATA ).getPendingExperimentSummaries(),
			isLoading: ! select( NAB_DATA ).isRecommendationEngineDataLoaded(),
			pendingCount:
				select( NAB_DATA ).getPendingExperimentSummaries().length,
		} ),
		[]
	);

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

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

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

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

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