/**
 * WordPress dependencies
 */
import { PanelBody, TextControl } from '@safe-wordpress/components';
import { useDispatch, useSelect } from '@safe-wordpress/data';
import { _x } from '@safe-wordpress/i18n';

/**
 * External dependencies
 */
import { usePluginSetting } from '@nab/data';

/**
 * Internal dependencies
 */
import { store as NAB_EDITOR } from '../../../store';

export const GA4Settings = (): JSX.Element | null => {
	const isGA4TrackingEnabled = usePluginSetting( 'isGA4TrackingEnabled' );
	const [ ga4Name, setGA4Name ] = useGA4ExperimentName();

	if ( ! isGA4TrackingEnabled ) {
		return null;
	}

	return (
		<PanelBody
			className="nab-experiment-ga4-settings"
			title={ _x( 'Google Analytics', 'text', 'nelio-ab-testing' ) }
			initialOpen={ !! ga4Name }
		>
			<TextControl
				label={ _x( 'Test Name', 'text', 'nelio-ab-testing' ) }
				className="nab-experiment-ga4-settings__text"
				value={ ga4Name }
				onChange={ setGA4Name }
				help={ _x( '', 'user', 'nelio-ab-testing' ) }
			/>
		</PanelBody>
	);
};

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

function useGA4ExperimentName(): [ string, ( name: string ) => void ] {
	const name = useSelect(
		( select ) => select( NAB_EDITOR ).getExtension( 'ga4Name' ) ?? '',
		[]
	);
	const { setExtension, removeExtension } = useDispatch( NAB_EDITOR );
	return [
		name,
		( newName: string ) =>
			! newName
				? removeExtension( 'ga4Name' )
				: setExtension( 'ga4Name', newName ),
	];
}
