/**
 * 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';
import { getBackgroundImageStyles, VideoBackground } from '@spectra-helpers/background';
import { spectraClassNames } from '@spectra-helpers';

/**
 * The render function for Login block.
 * Following loop-builder pattern with static template
 *
 * @param {Object} props The element props.
 * @since 2.0.0
 * @return {Element} Element to render.
 */
const Render = ( props ) => {
	const { attributes, clientId } = props;

	const {
		overallAlignment = 'left',
		usernameLabel = 'Username or Email',
		usernamePlaceholder = 'Enter your username or email',
		passwordLabel = 'Password',
		passwordPlaceholder = 'Enter your password',
		submitButtonText = 'Log In',
		showForgotPassword = true,
		forgotPasswordText = 'Forgot Password',
		showRegisterLink = false,
		registerLinkText = "Don't have an account? Register",
		showRegisterInfo = false,
		registerLinkUrl = {},
		welcomeMessage = 'Welcome Back',
		rememberMeText = 'Remember Me',
		showRememberMe = true,
		registerInfo = "Don't have an account?",
		// container width
		width,
		// Background-related attributes
		background,
		backgroundColor,
		backgroundGradient,
		backgroundGradientHover,
		dimRatio,
	} = attributes;

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

	// Configuration for the useSpectraStyles hook.
	const config = [
		{ key: 'textColor', cssVar: '--spectra-text-color', className: 'spectra-text-color' },
		{ key: 'backgroundColor', cssVar: '--spectra-background-color', className: 'spectra-background-color' },
		{ key: 'backgroundColorHover', cssVar: '--spectra-background-color-hover', className: 'spectra-background-color-hover' },
		{ key: 'backgroundGradient', cssVar: '--spectra-background-gradient', className: 'spectra-background-gradient' },
		{ key: 'backgroundGradientHover', cssVar: '--spectra-background-gradient-hover', className: 'spectra-background-gradient-hover' },
	];

	// Check if has video background and border radius.
	const hasVideoBackground = background?.type === 'video';
	const hasImageBackground = background?.type === 'image';

	// Custom class names for login block with background support
	const customClassNames = [
		'spectra-pro-login-form',
		'spectra-pro-form-container',
		'wp-block-button',
		[ 'image', 'video' ].includes( background?.type ) && `spectra-background-${ background.type }`,
		( backgroundColor || backgroundGradient ) && 'spectra-background-overlay',
		hasVideoBackground && 'has-video-background',
		hasImageBackground && 'has-image-background',
		`spectra-login-form--align-${overallAlignment}`,
		'spectra-overlay-color' // For overlay support
	];

	// Generate styles and class names
	const { style: generatedStyle, classNames: generatedClassNames } = useSpectraStyles( attributes, config );

	// Background styles handling.
	const getBackgroundStyles = () => {
		const styles = {
			...generatedStyle,
			...getBackgroundImageStyles( { background, backgroundGradient, backgroundGradientHover } ),
		};
		return styles;
	};

	// Apply form-specific custom properties
	const formStyles = {
		textAlign: overallAlignment,
		position: 'relative', // For overlay positioning
		display: 'flex',
		flexDirection: 'column',
		width,
		margin: '0 auto',
		...( typeof dimRatio === 'number' && ! isNaN( dimRatio ) ? { '--spectra-overlay-opacity': ( dimRatio / 100 ) } : {} ),
		...getBackgroundStyles(),
	};

	const blockProps = useBlockProps( {
		'className': spectraClassNames( [...customClassNames, ...generatedClassNames] ),
		'style': formStyles,
		'data-form-type': 'login'
	} );

	// Template for login form structure - following form-wrapper pattern
	const loginTemplate = useMemo( () => {
		// Helper function to create field template with nested children
		const createFieldTemplate = ( fieldType, labelText, placeholder, inputType = 'text', extraProps = {} ) => {
			const fieldChildren = [];

			// Always add label - it will hide itself via context when showLabels is false
			fieldChildren.push( [ 'spectra-pro/form-input-label', {
				labelText,
				fieldType
			} ] );

			// Create input group with icon and field wrapped together
			const inputGroupChildren = [];

			// Always add icon block - it will hide itself via context when showIcons is false
			// Don't set icon attribute here - form-icon block will use fieldType context to determine default
			// This allows custom icons to persist without being overwritten
			inputGroupChildren.push( [ 'spectra-pro/form-icon', {
				fieldType
			} ] );

			// Always add input field
			inputGroupChildren.push( [ 'spectra-pro/form-input-field', {
				inputType,
				placeholder,
				fieldType,
				...( inputType === 'password' && { autocomplete: 'off' } ),
				...extraProps
			} ] );

			// Wrap icon and input field in a form field wrapper for proper positioning
			fieldChildren.push( [ 'spectra-pro/form-field-wrapper', {
				fieldType
			}, inputGroupChildren ] );

			return [ 'spectra-pro/form-input-wrapper', {
				fieldType
			}, fieldChildren ];
		};


		// Build template without form-wrapper
		const template = [
			// Welcome message at the top
			[ 'spectra/content', {
				text: welcomeMessage,
				tagName: 'h2',
				className: 'spectra-pro-login-form__welcome-message'
			} ],

			// Form fields directly without wrapper
			createFieldTemplate( 'username', usernameLabel, usernamePlaceholder, 'text' ),
			createFieldTemplate( 'password', passwordLabel, passwordPlaceholder, 'password' ),

			// Remember me and forgot password wrapped in form-wrapper - MOVED ABOVE BUTTON
			...( ( showRememberMe || showForgotPassword ) ? [ [ 'spectra-pro/form-wrapper', {
				className: 'spectra-pro-login-form__remember-forgot-wrapper',
			}, [
				...( showRememberMe ? [ [ 'spectra-pro/form-checkbox', {
					fieldType: 'rememberme',
					checkboxLabel: rememberMeText
				} ] ] : [] ),
				...( showForgotPassword ? [ [ 'spectra-pro/form-link', {
					linkType: 'forgot_password',
					linkText: forgotPasswordText
				} ] ] : [] )
			] ] ] : [] ),

			[ 'spectra-pro/form-button', {
				text: submitButtonText,
				buttonType: 'submit'
			} ],

			// Form message blocks - always included, visibility controlled by CSS and demo toggles
			[ 'spectra-pro/form-message', {
				messageType: 'success'
			} ],
			[ 'spectra-pro/form-message', {
				messageType: 'error'
			} ],

			// Elements outside the form but inside the block
			...( showRegisterInfo ? [ [ 'spectra/content', {
				text: registerInfo,
				tagName: 'p',
				className: 'spectra-pro-login-form__register-text'
			} ] ] : [] ),
			...( showRegisterLink ? [ [ 'spectra-pro/form-link', {
				linkType: 'register_info',
				linkText: registerLinkText,
				url: registerLinkUrl
			} ] ] : [] )
		];

		return template;
	}, [ usernameLabel, usernamePlaceholder, passwordLabel, passwordPlaceholder, submitButtonText, showForgotPassword, forgotPasswordText, showRegisterLink, registerLinkText, showRegisterInfo, registerLinkUrl, welcomeMessage, rememberMeText, showRememberMe, registerInfo ] );

	return (
		<div { ...blockProps }>
			<InnerBlocks
				template={ loginTemplate }
				orientation="vertical"
				allowedBlocks={ [
					'spectra/content',
					'spectra-pro/form-wrapper',
					'spectra-pro/form-input-wrapper',
					'spectra-pro/form-field-wrapper',
					'spectra-pro/form-input-field',
					'spectra-pro/form-input-label',
					'spectra-pro/form-icon',
					'spectra-pro/form-checkbox',
					'spectra-pro/form-button',
					'spectra-pro/form-link',
					'spectra-pro/form-message'
				] }
				renderAppender={ hasChildBlocks ? undefined : InnerBlocks.ButtonBlockAppender }
			/>
			<VideoBackground { ...{ background } } />
		</div>
	);
};

export default memo( Render );