/**
 * WordPress dependencies
 */
import { useSelect } from '@safe-wordpress/data';
import { createInterpolateElement } from '@safe-wordpress/element';
import { _x, sprintf } from '@safe-wordpress/i18n';

/**
 * External dependencies
 */
import { store as NAB_DATA, usePluginSetting } from '@nab/data';
import { EMPTY_ARRAY } from '@nab/utils';
import type { Goal as RealGoal } from '@nab/types';

/**
 * Internal dependencies
 */
import { useExperimentAttribute } from '../hooks';

type GA4GoalSettings = Required<
	Required< RealGoal >[ 'attributes' ]
>[ 'ga4' ];

export function GA4Tracking(): JSX.Element | null {
	const isGA4TrackingEnabled = usePluginSetting( 'isGA4TrackingEnabled' );
	const settings = useGA4Settings();
	const {
		disabled: isGA4GoalTrackingDisabled,
		eventName: ga4EventName,
		goalName: ga4GoalName,
	} = settings;

	if ( ! isGA4TrackingEnabled ) {
		return null;
	}

	if ( isGA4GoalTrackingDisabled ) {
		return (
			<div className="nab-current-goal-info__ga4">
				<strong>Google Analytics Tracking.</strong>{ ' ' }
				{ _x(
					'This goal isn’t synced with Google Analytics.',
					'text',
					'nelio-ab-testing'
				) }
			</div>
		);
	}

	return (
		<div className="nab-current-goal-info__ga4">
			<strong>Google Analytics Tracking.</strong>{ ' ' }
			{ createInterpolateElement(
				ga4GoalName
					? sprintf(
							/* translators: %1$s: Event name. %2$s: Goal name. */
							_x(
								'This goal is synced with Google Analytics using the event %1$s and goal %2$s.',
								'text',
								'nelio-ab-testing'
							),
							`<code>${ ga4EventName || 'conversion' }</code>`,
							`<code>${ ga4GoalName }</code>`
					  )
					: sprintf(
							/* translators: %1$s: Event name. */
							_x(
								'This goal is synced with Google Analytics using the event %1$s.',
								'text',
								'nelio-ab-testing'
							),
							`<code>${ ga4EventName || 'conversion' }</code>`
					  ),
				{
					code: <code />,
				}
			) }
		</div>
	);
}

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

const DEFAULT_SETTINGS: GA4GoalSettings = {
	disabled: false,
	eventName: '',
	goalName: '',
};

function useGA4Settings(): GA4GoalSettings {
	const goals = useExperimentAttribute( 'goals' ) || EMPTY_ARRAY;
	const activeGoalId = useSelect(
		( select ) =>
			select( NAB_DATA ).getPageAttribute( 'editor/activeGoal' ) ??
			goals[ 0 ]?.id,
		[ goals ]
	);
	const goal = goals.find( ( g ) => g.id === activeGoalId );
	return goal?.attributes.ga4 || DEFAULT_SETTINGS;
}
