/**
 * External dependencies.
 */
import { useBlockProps, RichText } from '@wordpress/block-editor';
import { __ } from '@wordpress/i18n';
import { memo } from '@wordpress/element';

/**
 * Internal dependencies.
 */
import { useSpectraStyles } from '@spectra-hooks';

/**
 * The Editor Block render for Form Message.
 *
 * @param {Object} props The element props.
 * @since 2.0.0
 * @return {Element} The rendered block.
 */
const Render = ( props ) => {
	const {
		attributes: {
			messageType,
			messageText
		},
		context,
		setAttributes
	} = props;

	// Get context values
	const contextMessageType = context?.['spectra-pro/form/messageType'] || messageType;
	
	// Get message text based on message type and context
	let contextMessageText = messageText;
	if ( contextMessageType === 'success' ) {
		contextMessageText = context?.['spectra-pro/form/successMessageText'] || context?.['spectra-pro/form/messageSuccessRegistration'] || 'Registration successful!';
	} else if ( contextMessageType === 'error' ) {
		contextMessageText = context?.['spectra-pro/form/errorMessageText'] || context?.['spectra-pro/form/messageOtherError'] || 'An error occurred.';
	}

	// Get demo message toggle states from parent context
	const demoSuccessMessage = context?.['spectra-pro/form/demoSuccessMessage'] || false;
	const demoErrorMessage = context?.['spectra-pro/form/demoErrorMessage'] || false;

	// IMPORTANT: Always render message blocks in editor (they're part of the template)
	// Demo toggles only control CSS visibility for preview purposes
	// Determine if message should be visible based on demo toggles
	const isDemoVisible = () => {
		if ( contextMessageType === 'success' ) {
			return demoSuccessMessage;
		}
		if ( contextMessageType === 'error' ) {
			return demoErrorMessage;
		}
		// For other message types, default to visible
		return true;
	};

	// Get parent color context
	const parentSuccessMessageBg = context?.['spectra-pro/form/successMessageBackground'];
	const parentSuccessMessageColor = context?.['spectra-pro/form/successMessageColor'];
	const parentSuccessMessageBorder = context?.['spectra-pro/form/successMessageBorderColor'];
	const parentErrorMessageBg = context?.['spectra-pro/form/errorMessageBackground'];
	const parentErrorMessageColor = context?.['spectra-pro/form/errorMessageColor'];
	const parentErrorMessageBorder = context?.['spectra-pro/form/errorMessageBorderColor'];

	// Configuration for useSpectraStyles hook
	const config = [
		{ key: 'successMessageBackground', cssVar: '--spectra-success-message-background', className: 'spectra-success-message-background' },
		{ key: 'successMessageColor', cssVar: '--spectra-success-message-color', className: 'spectra-success-message-color' },
		{ key: 'successMessageBorderColor', cssVar: '--spectra-success-message-border-color', className: 'spectra-success-message-border-color' },
		{ key: 'errorMessageBackground', cssVar: '--spectra-error-message-background', className: 'spectra-error-message-background' },
		{ key: 'errorMessageColor', cssVar: '--spectra-error-message-color', className: 'spectra-error-message-color' },
		{ key: 'errorMessageBorderColor', cssVar: '--spectra-error-message-border-color', className: 'spectra-error-message-border-color' },
		{ key: 'textColor', cssVar: '--spectra-text-color', className: 'spectra-text-color' },
		{ key: 'backgroundColor', cssVar: '--spectra-background-color', className: 'spectra-background-color' }
	];

	// Merge local attributes with context values for useSpectraStyles
	const mergedAttributes = {
		...props.attributes,
		successMessageBackground: props.attributes.successMessageBackground || parentSuccessMessageBg,
		successMessageColor: props.attributes.successMessageColor || parentSuccessMessageColor,
		successMessageBorderColor: props.attributes.successMessageBorderColor || parentSuccessMessageBorder,
		errorMessageBackground: props.attributes.errorMessageBackground || parentErrorMessageBg,
		errorMessageColor: props.attributes.errorMessageColor || parentErrorMessageColor,
		errorMessageBorderColor: props.attributes.errorMessageBorderColor || parentErrorMessageBorder
	};

	// Get message icon based on type - using dashicons like v1
	const messageIcons = {
		success: 'dashicons-yes-alt',
		error: 'dashicons-warning',
		warning: 'dashicons-warning',
		info: 'dashicons-info',
	};
	const messageIconClass = messageIcons[contextMessageType] || messageIcons.info;

	// Custom class names - match frontend patterns from controller.php
	// Use demo visibility state for editor preview
	const isMessageVisible = isDemoVisible();
	const customClassNames = [
		`spectra-pro-form-message--${contextMessageType}`,
		isMessageVisible ? 'spectra-pro-form-message--visible' : 'spectra-pro-form-message--hidden'
	].filter( Boolean );

	// Generate styles and class names using useSpectraStyles hook
	const { style, classNames } = useSpectraStyles( mergedAttributes, config, customClassNames );

	// Use the block props with data-message-type attribute (matching frontend)
	const blockProps = useBlockProps( {
		'className': classNames,
		style,
		'data-message-type': contextMessageType
	} );

	return (
		<div { ...blockProps }>
			<div className="spectra-pro-form-message__wrapper">
				<div
					className="spectra-pro-form-message__content"
					role="alert"
					aria-live="polite"
					aria-atomic="true"
				>
					{/* Message icon - using dashicons like v1 */}
					{messageIconClass && (
						<span className={`dashicons ${messageIconClass}`}></span>
					)}
					
					<div className="spectra-pro-form-message__text-wrapper">
						<RichText
							tagName="span"
							className="spectra-pro-form-message__text"
							value={ contextMessageText }
							onChange={ ( value ) => setAttributes( { messageText: value } ) }
							placeholder={ __( 'Message text…', 'spectra-pro' ) }
							allowedFormats={ [ 'core/bold', 'core/italic' ] }
							withoutInteractiveFormatting
						/>
					</div>
				</div>
			</div>
		</div>
	);
};

export default memo( Render );