/**
 * WordPress dependencies
 */
import { useEffect, useState } from '@safe-wordpress/element';

/**
 * External dependencies
 */
import { AiGoogleAnalyticsData as UI } from '@nab/components';

/**
 * Internal dependencies
 */
import { DEFAULT_ATTRS } from './config';
import { useAttributes } from '../hooks';
import type { FieldSettingProps } from '../types';

export const GoogleAnalyticsDataSetting = ( {
	name: settingName,
	disabled,
}: FieldSettingProps ): JSX.Element => {
	const isAIEnabled = useIsAIEnabled();
	const [ attributes, setAttributes ] = useAttributes(
		settingName,
		DEFAULT_ATTRS
	);

	return (
		<>
			<UI
				disabled={ ! isAIEnabled || disabled }
				attributes={ attributes }
				setAttributes={ setAttributes }
			/>
			<input
				type="hidden"
				name={ settingName }
				value={ JSON.stringify( attributes ) }
			/>
		</>
	);
};

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

function useIsAIEnabled(): boolean {
	const element = document.getElementById(
		'nelio-ab-testing_settings_is-nelio-ai-enabled'
	) as HTMLInputElement | null;
	const [ enabled, setEnabled ] = useState( !! element?.checked );

	useEffect( () => {
		const toggle = () => setEnabled( !! element?.checked );
		element?.addEventListener( 'change', toggle );
		return () => element?.removeEventListener( 'change', toggle );
	}, [ element ] );

	return enabled;
}
