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

const HtmlEditorField = ( {field, value, onChange, allMetaData, fields} ) => {
	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' )
			} );
		}

		const lifecycleWarning = detectScriptLifecycleWarning( content, window?.adpressoAdminData?.docsUrlScriptLifecycle );
		if ( lifecycleWarning ) {
			msgs.push( lifecycleWarning );
		}

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

	// Suggest a matching TCF Vendor when the pasted code is recognizable as one of the big, known ad scripts.
	const vendorDetection = field.vendor_detection;
	const vendorOptions = useMemo(
		() => fields?.find( ( f ) => f.id === vendorDetection?.target_field )?.options || [],
		[fields, vendorDetection]
	);

	const detectedVendor = useMemo( () => {
		if ( !vendorDetection?.patterns || typeof value !== 'string' || !value.trim() ) {
			return null;
		}
		const content = value.toLowerCase();

		for ( const [keyword, needles] of Object.entries( vendorDetection.patterns ) ) {
			const isMatch = needles.some( ( needle ) => content.includes( String( needle ).toLowerCase() ) );
			if ( !isMatch ) {
				continue;
			}
			const option = vendorOptions.find(
				( opt ) => opt.value !== '0' && opt.label.toLowerCase().includes( keyword.toLowerCase() )
			);
			if ( option ) {
				return option;
			}
		}

		return null;
	}, [value, vendorDetection, vendorOptions] );

	const currentVendorValue = allMetaData?.[vendorDetection?.target_field];
	const showVendorSuggestion = Boolean( Number( allMetaData?.show_privacy_options ) )
		&& detectedVendor
		&& String( currentVendorValue ) !== String( detectedVendor.value );

	// Redirect-based click tracking (LinkRedirector) counts a click at the redirect itself; the frontend's own click listener must skip the same link instead.
	const frontendPrefix = window?.adpressoAdminData?.frontendPrefix || 'wpap';
	const clickSrcAttr = `data-${frontendPrefix}-click-src`;
	const content = typeof value === 'string' ? value : '';
	const isRedirectTracked = Boolean( Number( allMetaData?.redirect_click_tracking ) );
	const hasLinkPlaceholder = content.includes( '%link%' );
	const alreadyHasClickSrcAttr = content.includes( clickSrcAttr );
	const showRedirectTrackingNotice = hasLinkPlaceholder && isRedirectTracked && !alreadyHasClickSrcAttr;

	const handleInsertClickSrcAttribute = () => {
		const template = document.createElement( 'template' );
		template.innerHTML = content;
		const anchors = template.content.querySelectorAll( 'a[href="%link%"]' );

		if ( anchors.length === 0 ) {
			return;
		}

		anchors.forEach( ( anchor ) => anchor.setAttribute( clickSrcAttr, 'redirect' ) );
		onChange( field.id, template.innerHTML );
	};

	return (
		<div className="adpresso-html-editor-field">
			<ButtonGroup
				options={editorOptions}
				value={activeEditor}
				onChange={setActiveEditor}
			/>
			{showVendorSuggestion && (
				<div className="adpresso-notification-box">
					<div>
						<strong>{__( 'Automatic detection', 'adpresso' )}:</strong>{' '}
						{sprintf(
							/* translators: %s is the detected vendor name, e.g. "Google Advertising Products" */
							__( 'It looks like you\'ve inserted a %s script. Would you like to select it as the TCF Vendor for this ad?', 'adpresso' ),
							detectedVendor.label
						)}
						{' '}

						<Button
							variant="primary"
							onClick={() => onChange( vendorDetection.target_field, detectedVendor.value )}
							className="adpresso-btn adpresso-btn-action"
						>
							{sprintf(
								/* translators: %s is the detected vendor name, e.g. "Google Advertising Products" */
								__( 'Select %s', 'adpresso' ),
								detectedVendor.label
							)}
						</Button>
					</div>
				</div>
			)}
			{showRedirectTrackingNotice && (
				<div className="adpresso-notification-box adpresso-warning">
					<div>
						<strong>{__( 'Redirect click tracking', 'adpresso' )}:</strong>{' '}
						{__( 'Your code contains a %link% placeholder, and this ad has "Track Clicks via Redirect" enabled. Since you wrote this link\'s HTML tag yourself, we can\'t mark it automatically - without the marker, this click would be counted twice.', 'adpresso' )}
						{' '}
						<Button
							variant="primary"
							onClick={handleInsertClickSrcAttribute}
							className="adpresso-btn adpresso-btn-action"
						>
							{__( 'Insert tracking attribute now', 'adpresso' )}
						</Button>
					</div>
				</div>
			)}
			{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}
								{warning.link && (
									<>
										{' '}
										<a href={warning.link} target="_blank" rel="noopener noreferrer">
											{__( 'Learn more', 'adpresso' )}
										</a>
									</>
								)}
							</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;
