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

/**
 * External dependencies
 */
import { isDefined } from '@nab/utils';

/**
 * Internal dependencies
 */
import './style.scss';
import {
	AutomaticConversionActionList,
	ConversionActionList,
} from './conversion-action-list';
import { ConversionActionTypeList } from './conversion-action-type-list';
import { ECommerceGoalSettings } from './ecommerce-goal-settings';
import { GA4Settings } from './ga4-settings';
import { store as NAB_EDITOR } from '../../store';

export type GoalProps = {
	readonly isAutomatic: boolean;
	readonly name: string;
	readonly duplicateGoal?: () => void;
	readonly removeGoal?: () => void;
	readonly setName: ( name: string ) => void;
};

export const Goal = ( {
	name,
	setName,
	duplicateGoal,
	removeGoal,
	isAutomatic,
}: GoalProps ): JSX.Element => (
	<div className="nab-current-goal-info">
		{ ! isAutomatic && (
			<div className="nab-current-goal-info__header">
				<TextControl
					placeholder={ _x(
						'Name your goal…',
						'user',
						'nelio-ab-testing'
					) }
					value={ name }
					onChange={ ( value ) => setName( value ) }
				/>
				<Actions duplicate={ duplicateGoal } remove={ removeGoal } />
			</div>
		) }

		<ECommerceGoalSettings />
		<GA4Settings />

		{ isAutomatic ? (
			<AutomaticConversionActionList />
		) : (
			<>
				<ConversionActionList />
				<ConversionActionTypeList />
			</>
		) }
	</div>
);

const Actions = ( {
	duplicate,
	remove,
}: {
	readonly duplicate: GoalProps[ 'duplicateGoal' ];
	readonly remove: GoalProps[ 'removeGoal' ];
} ) => {
	const { openReusableDialog } = useDispatch( NAB_EDITOR );
	return (
		<DropdownMenu
			icon="admin-generic"
			label={ _x( 'Goal Actions', 'text', 'nelio-ab-testing' ) }
			controls={ [
				{
					title: _x( 'Save', 'command (goal)', 'nelio-ab-testing' ),
					icon: 'cloud' as const,
					onClick: () => openReusableDialog( 'save-goal' ),
				},
				duplicate
					? {
							title: _x(
								'Duplicate',
								'command (goal)',
								'nelio-ab-testing'
							),
							icon: 'admin-page' as const,
							onClick: duplicate,
					  }
					: undefined,
				remove
					? {
							title: _x(
								'Remove',
								'command (goal)',
								'nelio-ab-testing'
							),
							icon: 'trash' as const,
							onClick: remove,
					  }
					: undefined,
			].filter( isDefined ) }
		/>
	);
};
