/**
 * WordPress dependencies
 */
import '@safe-wordpress/notices';
import { dispatch, select } from '@safe-wordpress/data';
import domReady from '@safe-wordpress/dom-ready';
import { render } from '@safe-wordpress/element';

/**
 * External dependencies
 */
import { sortBy } from 'lodash';
import { store as NAB_DATA } from '@nab/data';
import { registerCoreExperiments } from '@nab/experiment-library';
import { registerCommands } from '@nab/commands';
import {
	PreviewUrlButton,
	TestCreationButtons,
	TitleAction,
} from '@nab/components';
import { createStagingNotice } from '@nab/utils';
import type { RunningExperimentSummary, SubscriptionPlan } from '@nab/types';

/**
 * Internal dependencies
 */
import './style.scss';
import { renderHelp } from './help';
import { Layout } from './components/layout';

type Settings = {
	readonly staging: 'environment-type' | 'url' | false;
	readonly experiments: ReadonlyArray< RunningExperimentSummary >;
	readonly heatmaps: ReadonlyArray< RunningExperimentSummary >;
	readonly subscription: SubscriptionPlan | false;
};

export function initPage( id: string, settings: Settings ): void {
	registerCoreExperiments();
	domReady( () => registerCommands() );

	const { staging, subscription, experiments, heatmaps } = settings;
	setRunningExperimentsInRecommendationEngine( [
		...experiments,
		...heatmaps,
	] );

	const titleAction = document.getElementById( `${ id }-title-action` );
	const content = document.getElementById( id );

	createStagingNotice( staging );
	render(
		<>
			<TestCreationButtons disableAi />
			<TitleAction isSubscribed={ !! subscription } />
			<PreviewUrlButton />
		</>,
		titleAction
	);

	render(
		<Layout experiments={ experiments } heatmaps={ heatmaps } />,
		content
	);

	renderHelp();
}

function setRunningExperimentsInRecommendationEngine(
	experiments: ReadonlyArray< RunningExperimentSummary >
) {
	const running = sortBy( experiments, 'startedAt' ).reverse();
	const state = select( NAB_DATA ).getRecommendationEngineState();
	void dispatch( NAB_DATA ).initRecommendationEngineData( {
		...state,
		experiments: {
			...state.experiments,
			runningCount: running.length,
			runningSummaries: running,
		},
	} );
}
