import { createRoot } from '@wordpress/element';
import { Eye, MousePointerClick, Percent, XCircle } from 'lucide-react';

import { AnalyticsChart } from './chart';
import type { BasicAnalytics } from './types';

let active:
	| {
			node: HTMLElement;
			root: ReturnType< typeof createRoot >;
	  }
	| undefined;

function Metric( {
	icon: Icon,
	label,
	value,
}: {
	icon: typeof Eye;
	label: string;
	value: string | number;
} ) {
	return (
		<article>
			<Icon aria-hidden="true" size={ 18 } strokeWidth={ 1.8 } />
			<span>{ label }</span>
			<strong>{ value }</strong>
		</article>
	);
}

function BasicAnalyticsPanel( { data }: { data: BasicAnalytics } ) {
	const hasActivity = data.impressions > 0 || data.clicks > 0;

	return (
		<>
			<div className="voidpulse-stats voidpulse-analytics-stats">
				<Metric
					icon={ Eye }
					label="Impressions"
					value={ data.impressions }
				/>
				<Metric
					icon={ MousePointerClick }
					label="Clicks"
					value={ data.clicks }
				/>
				<Metric
					icon={ XCircle }
					label="Dismissals"
					value={ data.dismissals }
				/>
				<Metric
					icon={ Percent }
					label="Click-through rate"
					value={ data.ctr + '%' }
				/>
			</div>
			<article className="voidpulse-card voidpulse-analytics-card">
				<div className="voidpulse-card-head">
					<div>
						<h2>{ `Last ${ data.days.length } days` }</h2>
						<p>
							Basic analytics are stored as daily totals in
							WordPress.
						</p>
					</div>
				</div>
				{ hasActivity ? (
					<AnalyticsChart days={ data.days } />
				) : (
					<div className="voidpulse-chart-empty">
						Your chart will appear after notifications have been
						shown.
					</div>
				) }
			</article>
		</>
	);
}

export function unmountBasicAnalytics() {
	if ( active ) {
		active.root.unmount();
		active = undefined;
	}
}

export function mountBasicAnalytics(
	node: HTMLElement | null,
	data: BasicAnalytics
) {
	if ( ! node ) {
		return;
	}
	if ( active && active.node !== node ) {
		unmountBasicAnalytics();
	}
	if ( ! active ) {
		active = { node, root: createRoot( node ) };
	}
	active.root.render( <BasicAnalyticsPanel data={ data } /> );
}
