/**
 * External dependencies.
 */
import {
	useBlockProps,
	InnerBlocks,
	store as blockEditorStore,
} from '@wordpress/block-editor';
import { memo, useMemo } from '@wordpress/element';
import { useSelect } from '@wordpress/data';

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

/**
 * The Editor Block render.
 *
 * @param {Object} props The element props.
 * @since 2.0.0
 * @return {Element} The rendered block.
 */
const Render = ( props ) => {
	const {
		clientId,
		context: {
			'spectra-pro/form/showIcons': showIcons,
			'spectra-pro/form-input/fieldType': contextFieldType,
			'spectra-pro/form-input/fieldIcon': contextFieldIcon,
			fieldType: legacyFieldType,
		},
		attributes,
	} = props;

	const fieldType = contextFieldType || legacyFieldType || 'text';
	const fieldIcon = contextFieldIcon;

	// Use useSelect hook for better performance instead of direct select() call
	const { hasChildBlocks } = useSelect( ( select ) => {
		const { getBlockOrder } = select( blockEditorStore );
		return {
			hasChildBlocks: getBlockOrder( clientId ).length > 0,
		};
	}, [ clientId ] );

	// Configuration for the useSpectraStyles hook
	const config = useMemo( () => [], [] );

	// Custom class names - simplified following WordPress patterns
	const customClassNames = [
		`spectra-form-field-wrapper--${fieldType}`,
		showIcons !== false && 'spectra-form-field-wrapper--has-icon',
	].filter( Boolean );

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

	// Use the block props, with the added CSS variables and their related classes.
	const blockProps = useBlockProps( {
		style,
		'className': classNames,
		'data-field-type': fieldType,
	} );

	// Get the icon based on field type
	const getIconForFieldType = ( type ) => {
		const iconMap = {
			username: 'user',
			email: 'envelope',
			password: 'lock',
			first_name: 'user',
			last_name: 'user',
			confirm_password: 'lock'
		};
		return iconMap[type] || 'user';
	};

	// Template for field wrapper: conditionally include icon based on showIcons context
	const fieldTemplate = useMemo( () => {
		const template = [];
		
		// Only include icon if showIcons is enabled (default to true if not set)
		if ( showIcons !== false ) {
			template.push( [ 'spectra-pro/form-icon', {
				icon: fieldIcon || getIconForFieldType( fieldType ),
				fieldType
			} ] );
		}
		
		// Always include the input field
		template.push( [ 'spectra-pro/form-input-field', {
			fieldType
		} ] );
		
		return template;
	}, [ fieldType, fieldIcon, showIcons ] );

	return (
		<div { ...blockProps }>
			<InnerBlocks
				template={ fieldTemplate }
				orientation="horizontal"
				allowedBlocks={ [
					'spectra-pro/form-icon',
					'spectra-pro/form-input-field'
				] }
				renderAppender={ hasChildBlocks ? undefined : InnerBlocks.ButtonBlockAppender }
			/>
		</div>
	);
};

export default memo( Render );