/**
 * WordPress dependencies
 */
import { useSelect } from '@wordpress/data';
import type { ExperimentId } from '@nab/types';

/**
 * Internal dependencies
 */
import { store as NAB_CHECKER } from '../store';
import { getGoalName, getTestName } from '../utils';
import type { ConversionEvent, ViewEvent } from '../store/types';
import type {
	ActiveExperimentSummary,
	InactiveExperimentSummary,
	HeatmapSummary,
} from '../../public/types';

export const Events = (): JSX.Element => {
	const events = useEventsWithExperiment();
	const isAwaitingGdpr = useSelect(
		( select ) => select( NAB_CHECKER ).isAwaitingGdpr(),
		[]
	);

	if ( isAwaitingGdpr ) {
		return <div style={ { marginTop: '1em' } }>Awaiting GDPR consent…</div>;
	}

	if ( ! events.length ) {
		return <div style={ { marginTop: '1em' } }>No Events</div>;
	}

	return (
		<div style={ { marginTop: '1em' } }>
			{ events.map( ( [ event, experiment ] ) => (
				<div key={ event.id } style={ { marginBottom: '0.6em' } }>
					{ stringify( event, experiment ) }
				</div>
			) ) }
		</div>
	);
};

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

function useEventsWithExperiment(): ReadonlyArray<
	[
		ViewEvent | ConversionEvent,
		ActiveExperimentSummary | InactiveExperimentSummary | HeatmapSummary,
	]
> {
	const { allEvents, experiments, heatmaps } = useSelect(
		( select ) => ( {
			allEvents: select( NAB_CHECKER ).getEvents(),
			experiments: select( NAB_CHECKER ).getSettings().experiments,
			heatmaps: select( NAB_CHECKER ).getSettings().heatmaps,
		} ),
		[]
	);

	const tests = [ ...experiments, ...heatmaps ].reduce(
		( r, t ) => ( {
			...r,
			[ t.id ]: t,
		} ),
		{} as Record<
			ExperimentId,
			ActiveExperimentSummary | InactiveExperimentSummary | HeatmapSummary
		>
	);

	return allEvents
		.map( ( e ) => [ e, tests[ e.experiment ] ] as const )
		.filter(
			(
				p
			): p is [
				ViewEvent | ConversionEvent,
				(
					| ActiveExperimentSummary
					| InactiveExperimentSummary
					| HeatmapSummary
				),
			] => !! p[ 1 ]
		);
}

// =======
// HELPERS
// =======

function stringify(
	event: ViewEvent | ConversionEvent,
	experiment:
		| ActiveExperimentSummary
		| InactiveExperimentSummary
		| HeatmapSummary
): string {
	// eslint-disable-next-line @wordpress/no-unused-vars-before-return
	const testName = getTestName( experiment );

	if ( 'goal' in event ) {
		if ( ! ( 'goals' in experiment ) ) {
			return '';
		}

		if ( 1 === experiment.goals.length ) {
			return `🎯 Conversion in ${ testName }`;
		}

		const goalName = getGoalName(
			'goals' in experiment ? experiment.goals[ event.goal ] : undefined,
			event.goal
		);
		return `🎯 Conversion of ${ goalName } in ${ testName }`;
	}

	return `👁️ View in ${ testName }`;
}
