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

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

/**
 * Internal dependencies
 */
import './style.scss';
import { OpportunityCard } from './opportunity-card';
import { ExperimentSuggestionsModal } from './experiment-suggestions-modal';

export function RecommendationSection(): JSX.Element | null {
	const {
		opportunities,
		isLoading,
		isAiActive,
		opportunityBeingInstantiated,
	} = useSelect(
		( select ) => ( {
			isAiActive: !! select( NAB_DATA ).getPluginSetting( 'aiSettings' ),
			isLoading: ! select( NAB_DATA ).isRecommendationEngineDataLoaded(),
			opportunities: select( NAB_DATA ).getOpportunities(),
			opportunityBeingInstantiated:
				select( NAB_DATA ).getOpportunityBeingInstantiated(),
		} ),
		[]
	);

	// eslint-disable-next-line no-nested-ternary
	const message = isLoading
		? _x( 'Finding opportunities…', 'text', 'nelio-ab-testing' )
		: opportunities.length
		? _x(
				'Recommended opportunities based on your site data and goals.',
				'text',
				'nelio-ab-testing'
		  )
		: _x( 'No recommendations at the moment.', 'text', 'nelio-ab-testing' );

	return (
		<section className="nab-recommendation-section nab-overview-card">
			<div className="nab-recommendation-section__header">
				<h2 className="nab-recommendation-section__title">
					<AiIcon gap="0.3em" />
					{ _x(
						'What should we test next?',
						'text',
						'nelio-ab-testing'
					) }
				</h2>
				<p className="nab-recommendation-section__description">
					{ message }
				</p>
			</div>

			{ !! opportunities.length && (
				<div className="nab-recommendation-section__scroller">
					<ol className="nab-recommendation-section__list">
						{ opportunities.map( ( opportunity, index ) => (
							<li
								className="nab-recommendation-section__item"
								key={ index }
							>
								<OpportunityCard
									opportunity={ opportunity }
									mode={
										// eslint-disable-next-line no-nested-ternary
										! isAiActive
											? opportunity ===
											  opportunityBeingInstantiated
												? 'creating-test'
												: 'create-test'
											: 'get-suggestions'
									}
									isDisabled={
										!! opportunityBeingInstantiated &&
										opportunityBeingInstantiated !==
											opportunity
									}
								/>
							</li>
						) ) }
					</ol>
				</div>
			) }

			<ExperimentSuggestionsModal />
		</section>
	);
}
