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

/**
 * External dependencies
 */
import { PostSearcher } from '@nab/components';
import type { ExperimentEditProps } from '@nab/types';

/**
 * Internal dependencies
 */
import './style.scss';
import type { ControlAttributes, AlternativeAttributes } from '../../types';

export type AlternativeProps = ExperimentEditProps< AlternativeAttributes > & {
	readonly placeholder?: string;
};

// NOTE. Dependency loop with @nab package.
import type { store as editorStore } from '@nab/editor';
const NAB_EDITOR = 'nab/editor' as unknown as typeof editorStore;

export const Alternative = ( {
	attributes,
	disabled,
	placeholder = _x( 'Describe your variant…', 'user', 'nelio-ab-testing' ),
	setAttributes,
}: AlternativeProps ): JSX.Element => {
	const isExistingContent = useExistingContent();

	useEffect( () => {
		setAttributes( {
			isExistingContent: isExistingContent ? true : undefined,
		} );
	}, [ isExistingContent, setAttributes ] );

	return isExistingContent ? (
		<>
			<PostSearcher
				disabled={ disabled }
				type="wp_block"
				value={ attributes.patternId }
				perPage={ 10 }
				onChange={ ( value ) =>
					// @ts-expect-error Pattern ID has the appropriate type.
					setAttributes( { patternId: value } )
				}
				placeholder={ _x(
					'Select variant…',
					'user',
					'nelio-ab-testing'
				) }
			/>
			{ !! attributes.unableToCreateVariant && (
				<Error error="unableToCreateVariant" />
			) }
		</>
	) : (
		<>
			<TextControl
				disabled={ disabled }
				value={ attributes.name }
				onChange={ ( value ) => setAttributes( { name: value } ) }
				placeholder={ placeholder }
			/>
			{ !! attributes.unableToCreateVariant && (
				<Error error="unableToCreateVariant" />
			) }
			{ /^https:/.test( attributes.name ) &&
				! attributes.unableToCreateVariant && (
					<Error error="urlIsNotAVariant" />
				) }
		</>
	);
};

// ============
// HELPER VIEWS
// ============

const Error = ( { error }: { error: keyof typeof ERRORS } ) => (
	<p className="nab-alternative-pattern-error">
		<Dashicon icon="warning" /> { ERRORS[ error ] }
	</p>
);

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

const useExistingContent = () =>
	!! useControl()?.attributes.testAgainstExistingPatterns;

const useControl = () =>
	useSelect(
		( select ) =>
			select( NAB_EDITOR ).getAlternative< ControlAttributes >(
				'control'
			),
		[]
	);

const ERRORS = {
	unableToCreateVariant: _x(
		'Something went wrong and this variant could not be properly created. Please reset it and save the test again to see if that fixes the issue. If it doesn’t, please get in touch with support.',
		'user',
		'nelio-ab-testing'
	),
	urlIsNotAVariant: _x(
		'It looks like you’re entering a URL. Variant names should describe your alternative content, not link to a page. If you want to test two already existing pages, please use a page test instead.',
		'user',
		'nelio-ab-testing'
	),
};
