/**
 * WordPress dependencies
 */
import { useSelect, useDispatch } from '@wordpress/data';

/**
 * Internal dependencies
 */
import { store as NAB_CHECKER } from '../store';
import { getTestName } from '../utils';
import { ClickEvent } from '../store/types';

export const HeatmapClicks = (): JSX.Element => {
	const {
		clicks: allClicks,
		experiments,
		heatmaps,
		isAwaitingGdpr,
	} = useSelect(
		( select ) => ( {
			clicks: select( NAB_CHECKER ).getHeatmapClicks(),
			experiments: select( NAB_CHECKER ).getSettings().experiments,
			heatmaps: select( NAB_CHECKER ).getSettings().heatmaps,
			isAwaitingGdpr: select( NAB_CHECKER ).isAwaitingGdpr(),
		} ),
		[]
	);

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

	const clicks = allClicks.slice( 0, 50 );
	const tests = [
		...experiments.filter( ( e ) => e.active && e.heatmapTracking ),
		...heatmaps,
	]
		.map( ( e ) => getTestName( e ) )
		.join( ', ' );

	return (
		<div>
			<div style={ { fontWeight: 700, margin: '1em 0' } }>
				Heatmap Events for { tests }
			</div>
			{ ! clicks.length ? (
				<div>None</div>
			) : (
				<ul>
					{ clicks.map( ( c ) => (
						<Click key={ c.id } attributes={ c } />
					) ) }
				</ul>
			) }
		</div>
	);
};

// =====
// VIEWS
// =====

function Click( { attributes }: { readonly attributes: ClickEvent } ) {
	const highlightedClick = useSelect(
		( select ) => select( NAB_CHECKER ).getHighlightedClick(),
		[]
	);
	const { setHighlightedClick } = useDispatch( NAB_CHECKER );

	const isActive = highlightedClick === attributes;
	const onClick = () =>
		setHighlightedClick( ! isActive ? attributes : undefined );

	return (
		<li>
			Click on{ ' ' }
			<button
				style={ {
					color: isActive ? '#ffb2b2' : '#c0cfff',
					margin: '0',
					padding: '0',
					background: 'none',
					border: 'none',
					cursor: 'pointer',
				} }
				onClick={ onClick }
			>
				<code>{ shorten( attributes.selector ) }</code>
			</button>
		</li>
	);
}

function shorten( s: string ): string {
	if ( s.length < 35 ) {
		return s;
	}

	return s.slice( 0, 10 ) + '…' + s.slice( s.length - 24, s.length );
}
