/**
 * External dependencies.
 */
import { TextControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useState, useEffect } from '@wordpress/element';

/**
 * Internal dependencies.
 */
import CustomSelectControl from '@spectra-pro-components/CustomSelectControl';
import urls from '@spectra-pro-constants/urls';
import API from '@spectra-pro-helpers/api';

/**
 * Renders controls for selecting or entering a user-related field for dynamic content.
 *
 * Displays a select control with default user fields and fetched meta fields when the
 * data source is 'current_user'. Includes a text input for custom meta keys when selected.
 * Updates the dynamic content settings with the selected or entered field.
 *
 * @since x.x.x
 *
 * @param {Object}   props               - The component props.
 * @param {Object}   props.settings      - The dynamic content settings from the context.
 * @param {Function} props.updateSetting - Function to update settings in the context.
 * @return {Element} The user field selection controls.
 */
const UserField = ( { settings, updateSetting } ) => {
	// State for available user meta keys and loading status.
	const [ userMetaKeys, setUserMetaKeys ] = useState( [] );
	const [ isLoading, setIsLoading ] = useState( true );

	// Default user fields for selection.
	const defaultUserFields = [
		{ label: __( 'Display Name', 'spectra-pro' ), value: 'display_name' },
		{ label: __( 'Username', 'spectra-pro' ), value: 'login' },
		{ value: 'nicename', label: __( 'Nickname', 'spectra-pro' ) },
		{ label: __( 'First Name', 'spectra-pro' ), value: 'first_name' },
		{ label: __( 'Last Name', 'spectra-pro' ), value: 'last_name' },
		{ label: __( 'Bio', 'spectra-pro' ), value: 'description' },
		{ label: __( 'Email', 'spectra-pro' ), value: 'email' },
		{ label: __( 'ID', 'spectra-pro' ), value: 'id' },
		{ label: __( 'Website', 'spectra-pro' ), value: 'url' },
		{ label: __( 'Avatar Image URL', 'spectra-pro' ), value: 'avatar' },
	];

	// Initialize API client for fetching user custom fields.
	const userCustomFieldsAPI = new API( urls.userCustomFields );

	// Fetch user meta fields when the source is 'current_user'.
	useEffect( () => {
		if ( settings.source.type !== 'current_user' ) {
			setUserMetaKeys( [] );
			setIsLoading( false );
			return;
		}

		/**
		 * Fetches available user meta fields.
		 */
		const fetchUserData = async () => {
			try {
				setIsLoading( true );
				// Fetch user meta fields via API.
				const response = await userCustomFieldsAPI.list();

				// Transform response data into select options.
				const userFields = Object.entries( response?.data || {} )
					.map( ( [ , val ] ) => {
						if ( val && typeof val === 'object' && 'label' in val && 'value' in val ) {
							return {
								label: val.label,
								value: val.value,
							};
						}

						return null;
					} )
					.filter( Boolean );

				setUserMetaKeys( userFields );
			} catch ( error ) {
				// Fallback to empty array if fetch fails.
				setUserMetaKeys( [] );
			} finally {
				setIsLoading( false );
			}
		};

		fetchUserData();
	}, [ settings.source.type ] );

	const mergedFields = [
		...defaultUserFields,
		...userMetaKeys,
		{ label: __( 'Custom Input', 'spectra-pro' ), value: 'custom_input' },
	];

	return (
		<>
			{ /* Select control for choosing a user field */ }
			<CustomSelectControl
				label={ __( 'Custom Field', 'spectra-pro' ) }
				value={ settings.source.field }
				options={ isLoading ? [ { label: __( 'Loading…', 'spectra-pro' ), value: '' } ] : mergedFields }
				onChange={ ( newValue ) => updateSetting( 'source.field', newValue ) }
				disabled={ isLoading } // Disable while loading.
			/>
			{ /* Text input for custom meta key when 'custom_input' is selected */ }
			{ settings.source.field === 'custom_input' && ! isLoading && (
				<TextControl
					label={ __( 'Custom Meta Key', 'spectra-pro' ) }
					value={ settings.source.userMetaKey || '' }
					onChange={ ( newValue ) => updateSetting( 'source.userMetaKey', newValue ) }
					help={ __( 'Enter a custom meta key', 'spectra-pro' ) }
				/>
			) }
		</>
	);
};

export default UserField;
