/**
 * WordPress dependencies
 */
import { NoticeList } from '@safe-wordpress/components';
import { useSelect } from '@safe-wordpress/data';
import { useState } from '@safe-wordpress/element';
import { store as NOTICES } from '@safe-wordpress/notices';
import {
	addQueryArgs,
	getQueryArgs,
	removeQueryArgs,
} from '@safe-wordpress/url';

/**
 * External dependencies
 */
import type { RunningExperimentSummary } from '@nab/types';

/**
 * Internal dependencies
 */
import './style.scss';
import { ExperimentSection } from '../experiment-section';
import { OptimizationScoreAndQuota } from '../optimization-score-and-quota';
import { RecommendationSection } from '../recommendation-section';
import { NoQuotaWarning } from '../no-quota-warning';

import { ExtendedRunningExperiments } from '../extended-running-experiments';

type LayoutProps = {
	readonly experiments: ReadonlyArray< RunningExperimentSummary >;
	readonly heatmaps: ReadonlyArray< RunningExperimentSummary >;
};

const EXTENDED_VIEW_PARAM = 'nab-extended-running-view';

export const Layout = ( {
	experiments,
	heatmaps,
}: LayoutProps ): JSX.Element => {
	const notices = useNotices();

	const url = window.location.href;
	const [
		isExtendedRunningExperimentsActive,
		activateExtendedRunningExperiments,
	] = useState( !! getQueryArgs( url )[ EXTENDED_VIEW_PARAM ] );
	const count = experiments.length + heatmaps.length;

	const activateExtendedView = ( active: boolean ) => {
		window.history.replaceState(
			{},
			'',
			active
				? addQueryArgs( url, { [ EXTENDED_VIEW_PARAM ]: true } )
				: removeQueryArgs( url, EXTENDED_VIEW_PARAM )
		);
		activateExtendedRunningExperiments( active );
	};

	if ( isExtendedRunningExperimentsActive && !! count ) {
		return (
			<div className="nab-overview">
				<NoticeList notices={ notices } />
				<ExtendedRunningExperiments
					experiments={ experiments }
					heatmaps={ heatmaps }
					onBackClicked={ () => activateExtendedView( false ) }
				/>
			</div>
		);
	}

	return (
		<div className="nab-overview">
			<NoticeList notices={ notices } />
			<div className="nab-overview-content">
				<NoQuotaWarning />
				<OptimizationScoreAndQuota />
				<RecommendationSection />
				<ExperimentSection
					onExtendedClicked={ () => activateExtendedView( true ) }
				/>
			</div>
		</div>
	);
};

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

const useNotices = () =>
	useSelect( ( select ) => select( NOTICES ).getNotices(), [] );
