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

/**
 * Internal dependencies.
 */
import { useSpectraStyles } from '@spectra-hooks';
import { getBackgroundImageStyles, VideoBackground } from '@spectra-helpers/background';
import { spectraClassNames } from '@spectra-helpers';

/**
 * The render function for Register 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',
		welcomeMessage = 'Register New Account',
		registerButtonLabel = 'Register',
		loginLinkLabel = 'Already have an account? Login',
		showLoginInfo = false,
		btnLoginLink = { url: '', opensInNewTab: false },
		showPrivacyPolicy = true,
		// container width
		width,
		// Background-related attributes
		background,
		backgroundColor,
		backgroundGradient,
		backgroundGradientHover,
		dimRatio,
	} = attributes;

	// Use useSelect hook for better performance and get registration setting from localized data
	const { hasChildBlocks } = useSelect( ( select ) => {
		const { getBlockOrder, getBlocks } = select( blockEditorStore );
		const blockOrder = getBlockOrder( clientId );

		return {
			hasChildBlocks: blockOrder.length > 0,
			childBlocks: getBlocks( clientId ),
		};
	}, [ clientId ] );

	// Get registration setting from localized data
	const usersCanRegister = window.spectra_pro_blocks_info?.is_allow_registration || false;

	// Handler to open settings link.
	const handleSettingsLinkClick = ( event ) => {
		event.preventDefault();
		const url = window.spectra_pro_blocks_info?.anyone_can_register;
		if ( url ) {
			window.open( url, '_blank', 'noopener,noreferrer' );
		}
	};

	// Note: Message blocks are now always in the template
	// Demo toggles (demoSuccessMessage, demoErrorMessage) control visibility via context
	// The form-message block's render.js handles the visibility based on these demo toggles

	// 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 register block with background support
	const customClassNames = [
		'spectra-pro-register-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-register-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',
		gap: '0px',
		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': 'register'
	} );

	// Template for register form structure using new field-specific blocks
	const registerTemplate = useMemo( () => {
		// Build template with field-specific wrapper blocks for better user control
		const template = [
			// Welcome message at the top
			[ 'spectra/content', {
				text: welcomeMessage,
				tagName: 'h2',
				className: 'spectra-pro-register-form__welcome-message'
			} ],
			// Core required fields using new field-specific blocks
			[ 'spectra-pro/register-user-name' ],
			[ 'spectra-pro/register-email' ],
			[ 'spectra-pro/register-password' ],

			// Submit button
			[ 'spectra-pro/form-button', {
				text: registerButtonLabel,
				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'
			} ],

			// Optional login link
			...( showLoginInfo ? [[ 'spectra-pro/form-link', {
				text: loginLinkLabel,
				linkType: 'login_info',
				url: btnLoginLink?.url || '#',
				opensInNewTab: btnLoginLink?.opensInNewTab || false
			} ]] : [] )
		];

		return template;
	}, [ registerButtonLabel, loginLinkLabel, showLoginInfo, btnLoginLink, showPrivacyPolicy, welcomeMessage ] );


	return (
		<div { ...blockProps }>
			{ ! usersCanRegister && (
				<Notice status="warning" className="spectra-sidebar-settings-notice" isDismissible={ false }>
					{ createInterpolateElement(
						__( 'To use Registration Form on your site, please enable the "<SettingsLink>Anyone Can Register</SettingsLink>" setting from Dashboard -> Settings -> General -> Membership.', 'spectra-pro' ),
						{
							SettingsLink: (
								<Button
									variant="link"
									onClick={ handleSettingsLinkClick }
									style={{ padding:0 }}
								/>
							),
						}
					) }
				</Notice>
			) }
			<InnerBlocks
				template={ registerTemplate }
				orientation="vertical"
				allowedBlocks={ [
					'spectra/content',
					'spectra-pro/register-user-name',
					'spectra-pro/register-email',
					'spectra-pro/register-password',
					'spectra-pro/register-confirm-password',
					'spectra-pro/register-first-name',
					'spectra-pro/register-last-name',
					'spectra-pro/form-input-wrapper',
					'spectra-pro/form-input-field',
					'spectra-pro/form-input-label',
					'spectra-pro/form-icon',
					'spectra-pro/register-terms-and-conditions',
					'spectra-pro/form-button',
					'spectra-pro/form-link',
					'spectra-pro/form-message'
				] }
				renderAppender={ hasChildBlocks ? undefined : InnerBlocks.ButtonBlockAppender }
			/>
			<VideoBackground { ...{ background } } />
		</div>
	);
};

export default memo( Render );