import {useMemo, useState} from '@wordpress/element';
import {__} from '@wordpress/i18n';
import ButtonGroup from '../../../../design/components/ButtonGroup';
import CodeMirrorEditor from '../editor/CodeMirrorEditor';
import ClassicEditor from '../editor/ClassicEditor';
// import GutenbergEditor from '../editor/GutenbergEditor';
import './GutenbergEditor.scss';

const HtmlEditorField = ( {field, value, onChange, allMetaData} ) => {
	const [activeEditor, setActiveEditor] = useState( 'text' );
	const editorOptions = [
		{key: 'text', label: __( 'Plain Text', 'adpresso' )},
		{key: 'classic', label: __( 'Classic Editor', 'adpresso' )}
		// { key: 'gutenberg', label: __('Block Editor', 'adpresso') },
	];

	const targetUrl = allMetaData?.target_url || '';

	const warnings = useMemo( () => {
		const msgs = [];
		const content = typeof value === 'string' ? value : '';
		const url = typeof targetUrl === 'string' ? targetUrl.trim() : '';
		const hasPlaceholder = content.includes( '%link%' );
		const hasAnchor = content.toLowerCase().includes( '<a ' );
		const hasUrl = url !== '';

		if ( hasPlaceholder && !hasUrl ) {
			msgs.push( {
				type: 'error',
				text: __( 'You\'re using the %link% parameter in the code, but you haven\'t defined a target URL. The link will lead nowhere.', 'adpresso' )
			} );
		}

		if ( hasUrl && hasAnchor && !hasPlaceholder ) {
			msgs.push( {
				type: 'warning',
				text: __( 'Your code already contains its own links (<a> tags). Since you’ve also specified a target URL, your code is being wrapped again. This results in invalid HTML. Please insert %link% at the desired location in the code or remove the target URL.', 'adpresso' )
			} );
		}

		return msgs;
	}, [value, targetUrl] );

	return (
		<div className="adpresso-html-editor-field">
			<ButtonGroup
				options={editorOptions}
				value={activeEditor}
				onChange={setActiveEditor}
			/>
			{warnings.length > 0 && (
				<>
					{warnings.map( ( warning, index ) => (
						<div key={index} className={`adpresso-notification-box adpresso-${warning.type}`}>
							<p>
								<strong>{warning.type === 'error' ? __( 'Error', 'adpresso' ) : __( 'Notice', 'adpresso' )}: </strong>
								{warning.text}
							</p>
						</div>
					) )}
				</>
			)}
			<div className="adpresso-editor-content-wrapper">
				<div style={{display: activeEditor === 'text' ? 'block' : 'none'}}>
					<CodeMirrorEditor
						value={value}
						onChange={( newValue ) => {
							if ( activeEditor === 'text' ) {
								onChange( field.id, newValue );
							}
						}}
						isActive={activeEditor === 'text'}
					/>
				</div>
				<div style={{display: activeEditor === 'classic' ? 'block' : 'none'}}>
					<ClassicEditor
						value={value}
						onChange={( newValue ) => {
							if ( activeEditor === 'classic' ) {
								onChange( field.id, newValue );
							}
						}}
						isActive={activeEditor === 'classic'}
					/>
				</div>
			</div>
		</div>
	);
};

export default HtmlEditorField;
