/**
 * WordPress dependencies
 */
import domReady from '@safe-wordpress/dom-ready';
import { render } from '@safe-wordpress/element';
import { addQueryArgs } from '@safe-wordpress/url';

/**
 * External dependencies
 */
import { map } from 'lodash';

/**
 * Internal dependencies
 */
import { ButtonProps, ContextualHelp, ContentProps } from './contextual-help';
import type { Question, TutorialStep } from './types';

type Args = {
	readonly screen: string;
	readonly questions: ReadonlyArray< Question >;
	readonly walkthrough?: ReadonlyArray< TutorialStep >;
};

export * from './types';

export type ContextualHelpContentProps = Omit< ContentProps, 'mode' >;
export const ContextualHelpContent = (
	props: ContextualHelpContentProps
): JSX.Element => <ContextualHelp mode="content" { ...props } />;

export type ContextualHelpButtonProps = Omit< ButtonProps, 'mode' >;
export const ContextualHelpButton = (
	props: ContextualHelpButtonProps
): JSX.Element => <ContextualHelp mode="button" { ...props } />;

export function appendContextualHelp( {
	screen,
	questions,
	walkthrough = [],
}: Args ): void {
	domReady( () => {
		const helpTab = document.getElementById( 'tab-panel-nelio-ab-testing' );
		const wrapper = document.createElement( 'div' );
		if ( helpTab ) {
			helpTab.innerHTML = '';
			helpTab.appendChild( wrapper );
		} else {
			document.body.appendChild( wrapper );
		}

		const closeHelpTab = () => {
			const button = document.querySelector< HTMLAnchorElement >(
				'#contextual-help-link.screen-meta-active'
			);
			button?.click();
		};

		render(
			helpTab ? (
				<ContextualHelp
					mode="content"
					screen={ screen }
					questions={ map( questions, addUtmArgs( screen ) ) }
					walkthrough={ walkthrough ?? [] }
					onCloseForm={ closeHelpTab }
					onRunWalkthrough={ closeHelpTab }
				/>
			) : (
				<ContextualHelp
					mode="floating"
					screen={ screen }
					questions={ map( questions, addUtmArgs( screen ) ) }
					walkthrough={ walkthrough ?? [] }
				/>
			),
			wrapper
		);
	} );
}

// =======
// HELPERS
// =======

const addUtmArgs = ( screen: string ) => ( question: Question ) => ( {
	...question,
	link: addQueryArgs( question.link, {
		utm_source: 'nelio-ab-testing',
		utm_medium: 'plugin',
		utm_campaign: 'support',
		utm_content: `${ screen }-page`,
	} ),
} );
