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

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

/**
 * The Editor Block render for Form Input Field.
 *
 * @param {Object} props The element props.
 * @since 2.0.0
 * @return {Element} The rendered block.
 */
const Render = ( props ) => {
	const {
		attributes: {
			inputType,
			placeholder,
			isRequired,
			isDisabled,
			maxLength,
			minLength,
			pattern,
			autocomplete
		},
		setAttributes,
		context
	} = props;

	// Get context values
	const {
		'spectra-pro/form-input/fieldType': fieldType,
		'spectra-pro/form-input/fieldPlaceholder': fieldPlaceholder,
		'spectra-pro/form-input/fieldId': fieldId,
		'spectra-pro/form-input/isRequired': contextRequired
	} = context || {};

	// State for password visibility
	const [isPasswordVisible, setIsPasswordVisible] = useState( false );

	// Set input type based on field type from context
	useEffect( () => {
		if ( fieldType && ! inputType ) {
			const inputTypes = {
				username: 'text',
				email: 'email',
				password: 'password',
				first_name: 'text',
				last_name: 'text',
				confirm_password: 'password',
				text: 'text'
			};
			setAttributes( { inputType: inputTypes[ fieldType ] || 'text' } );
		}
	}, [ fieldType, inputType ] );

	// Always sync placeholder from context (parent form-input-wrapper)
	useEffect( () => {
		if ( fieldPlaceholder !== undefined && fieldPlaceholder !== placeholder ) {
			setAttributes( { placeholder: fieldPlaceholder } );
		}
	}, [ fieldPlaceholder ] );

	// Set required state from context if not explicitly set
	useEffect( () => {
		if ( contextRequired !== undefined && isRequired !== contextRequired ) {
			setAttributes( { isRequired: contextRequired } );
		}
	}, [ contextRequired, isRequired ] );

	// Set autocomplete attribute based on field type
	useEffect( () => {
		if ( fieldType && ! autocomplete ) {
			const autocompleteValues = {
				username: 'username',
				email: 'email',
				password: 'current-password',
				first_name: 'given-name',
				last_name: 'family-name',
				confirm_password: 'new-password'
			};
			if ( autocompleteValues[ fieldType ] ) {
				setAttributes( { autocomplete: autocompleteValues[ fieldType ] } );
			}
		}
	}, [ fieldType, autocomplete ] );

	// Determine if we should show password toggle
	const isPasswordField = inputType === 'password';
	const shouldShowToggle = isPasswordField;

	// Get parent color context
	const parentInputTextColor = context?.['spectra-pro/form/inputTextColor'];
	const parentInputTextColorHover = context?.['spectra-pro/form/inputTextColorHover'];
	const parentInputBgColor = context?.['spectra-pro/form/inputBgColor'];
	const parentInputBgColorHover = context?.['spectra-pro/form/inputBgColorHover'];
	const parentInputPlaceholderColor = context?.['spectra-pro/form/inputPlaceholderColor'];
	const parentInputPlaceholderColorHover = context?.['spectra-pro/form/inputPlaceholderColorHover'];

	// Configuration for useSpectraStyles hook
	const config = [
		{ key: 'textColor', cssVar: '--spectra-input-text-color', className: 'spectra-input-text-color' },
		{ key: 'textColorHover', cssVar: '--spectra-input-text-color-hover', className: 'spectra-input-text-color-hover' },
		{ key: 'backgroundColor', cssVar: '--spectra-input-bg-color', className: 'spectra-input-bg-color' },
		{ key: 'backgroundColorHover', cssVar: '--spectra-input-bg-color-hover', className: 'spectra-input-bg-color-hover' },
		{ key: 'placeholderColor', cssVar: '--spectra-input-placeholder-color', className: 'spectra-input-placeholder-color' },
		{ key: 'placeholderColorHover', cssVar: '--spectra-input-placeholder-color-hover', className: 'spectra-input-placeholder-color-hover' },
	];

	// Merge local attributes with context values for useSpectraStyles
	const mergedAttributes = {
		...props.attributes,
		textColor: props.attributes.textColor || parentInputTextColor,
		textColorHover: props.attributes.textColorHover || parentInputTextColorHover,
		backgroundColor: props.attributes.backgroundColor || parentInputBgColor,
		backgroundColorHover: props.attributes.backgroundColorHover || parentInputBgColorHover,
		placeholderColor: props.attributes.placeholderColor || parentInputPlaceholderColor,
		placeholderColorHover: props.attributes.placeholderColorHover || parentInputPlaceholderColorHover
	};

	// Custom class names - simplified following WordPress patterns
	const customClassNames = [
		`spectra-form-input-field--${inputType}`,
		shouldShowToggle && 'spectra-form-input-field--has-toggle'
	].filter( Boolean );

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

	const blockProps = useBlockProps( {
		type: isPasswordField && isPasswordVisible ? 'text' : inputType,
		placeholder: placeholder !== undefined ? placeholder : ( fieldPlaceholder || '' ),
		required: isRequired || contextRequired,
		disabled: isDisabled,
		maxLength,
		minLength,
		pattern,
		autoComplete: autocomplete,
		id: fieldId,
		name: fieldType || 'input',
		className: `spectra-form-input-field__input ${Array.isArray( classNames ) ? classNames.join( ' ' ) : classNames}`,
		style,
	} );


	// SVG icons for password toggle
	const EyeIcon = () => (
		<svg 
			focusable="false" 
			style={{ fill: 'currentColor', width: '16px', height: '16px' }}
			className="spectra-pro-password-toggle__icon"
			data-icon-type="visible"
			viewBox="0 0 24 24"
		>
			<path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/>
		</svg>
	);

	const EyeOffIcon = () => (
		<svg
			focusable="false"
			style={{ fill: 'currentColor', width: '16px', height: '16px' }}
			className="spectra-pro-password-toggle__icon"
			data-icon-type="hidden"
			viewBox="0 0 24 24"
		>
			<path d="M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z"/>
		</svg>
	);

	// Password toggle button
	const renderPasswordToggle = () => {
		if ( ! shouldShowToggle ) {
			return null;
		}

		return (
			<button
				type="button"
				className="spectra-pro-form-input-field__password-toggle"
				onClick={() => setIsPasswordVisible( !isPasswordVisible )}
				aria-label={isPasswordVisible ? __( 'Hide Password', 'spectra-pro' ) : __( 'Show Password', 'spectra-pro' )}
			>
				{!isPasswordVisible && <EyeIcon />}
				{isPasswordVisible && <EyeOffIcon />}
			</button>
		);
	};

	return (
		<>
			<input { ...blockProps } />
			{ renderPasswordToggle() }
		</>
	);
};

export default memo( Render );