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

/**
 * Internal dependencies
 */
import { store as NAB_CHECKER } from '../store';
import { State } from '../store/types';

export const Tabs = (): JSX.Element => (
	<div style={ TABS_STYLE }>
		<Tab name="status" label="Status" />
		<Tab name="experiments" label="Tests" />
		<EventsTab />
		<HeatmapClicksTab />
	</div>
);

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

function Tab( { name, label }: { name: State[ 'tab' ]; label: string } ) {
	const activeTab = useSelect(
		( select ) => select( NAB_CHECKER ).getTab(),
		[]
	);
	const { setTab } = useDispatch( NAB_CHECKER );

	return (
		<button
			onClick={ () => setTab( name ) }
			disabled={ name === activeTab }
		>
			{ label }
		</button>
	);
}

function EventsTab() {
	const { activeTab, currentEvents } = useSelect(
		( select ) => ( {
			activeTab: select( NAB_CHECKER ).getTab(),
			currentEvents: select( NAB_CHECKER ).getEvents(),
		} ),
		[]
	);
	const [ previousEvents, setPreviousEvents ] = useState( currentEvents );

	useEffect( () => {
		if ( 'events' === activeTab && currentEvents !== previousEvents ) {
			setPreviousEvents( currentEvents );
		}
	}, [ activeTab, currentEvents, previousEvents, setPreviousEvents ] );

	const label =
		'events' !== activeTab && currentEvents !== previousEvents
			? 'Events •'
			: 'Events';

	return <Tab name="events" label={ label } />;
}

function HeatmapClicksTab() {
	const { activeTab, currentClicks, settings } = useSelect(
		( select ) => ( {
			activeTab: select( NAB_CHECKER ).getTab(),
			currentClicks: select( NAB_CHECKER ).getHeatmapClicks(),
			settings: select( NAB_CHECKER ).getSettings(),
		} ),
		[]
	);
	const [ previousClicks, setPreviousClicks ] = useState( currentClicks );

	useEffect( () => {
		if (
			'heatmap-clicks' === activeTab &&
			currentClicks !== previousClicks
		) {
			setPreviousClicks( currentClicks );
		}
	}, [ activeTab, currentClicks, previousClicks, setPreviousClicks ] );

	if (
		! settings.heatmaps.length &&
		! settings.experiments.some( ( e ) => e.active && e.heatmapTracking )
	) {
		return null;
	}

	const label =
		'heatmap-clicks' !== activeTab && currentClicks !== previousClicks
			? 'Heatmap •'
			: 'Heatmap';

	return <Tab name="heatmap-clicks" label={ label } />;
}

// ======
// STYLES
// ======

const TABS_STYLE = {
	display: 'flex',
	gap: '0.5em',
};
