/**
 * External dependencies.
 */
import { SelectControl, TextControl } from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import { store as editorStore } from '@wordpress/editor';
import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

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

/**
 * Renders controls for selecting or entering a post-related custom meta key.
 *
 * Displays a select control with available meta fields for the current or specified post
 * and a text input for custom meta keys when selected. Updates the dynamic content settings
 * with the selected or entered meta key.
 *
 * @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.
 * @param {string}   [props.type='text'] - The type of content ('text' or 'image').
 * @return {Element} The meta field selection controls.
 */
const MetaField = ( { settings, updateSetting, type = 'text' } ) => {
	// State for loading status and available meta keys.
	const [ isLoading, setIsLoading ] = useState( true );
	const [ metaKeys, setMetaKeys ] = useState( [
		{ label: __( 'Choose', 'spectra-pro' ), value: '' },
		{ label: __( 'Custom Input', 'spectra-pro' ), value: 'custom' },
	] );

	// Extract the selected meta key from settings.
	const selectedMetaKey = settings.source.postCustomField || '';

	// Get the current post ID from the editor store.
	const currentPostId = useSelect( ( select ) => select( editorStore ).getCurrentPostId(), [] );

	// Determine post ID based on source type.
	let postId = null;
	if ( settings.source.type === 'current_post' ) {
		postId = currentPostId;
	} else if ( settings.source.type === 'post_type' ) {
		postId = settings.source.postId;
	}

	// Initialize API client for fetching post custom fields.
	const postCustomFieldsAPI = new API( urls.postCustomFields );

	// Fetch meta fields when post ID changes.
	useEffect( () => {
		if ( ! postId ) {
			setIsLoading( false );
			return;
		}

		/**
		 * Fetches available meta fields for the specified post.
		 */
		const fetchMetaFields = async () => {
			setIsLoading( true );

			try {
				// Fetch meta fields via API.
				const response = await postCustomFieldsAPI.list( { post_id: postId, type } );

				// Transform response data into select options.
				const metaFields = 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 );

				// Combine default options with fetched meta fields.
				const metaOptions = [
					{ label: __( 'Choose', 'spectra-pro' ), value: '' },
					...metaFields,
					{ label: __( 'Custom Input', 'spectra-pro' ), value: 'custom' },
				];

				setMetaKeys( metaOptions );
			} catch ( error ) {
				// Clear meta keys on error.
				setMetaKeys( [] );
			} finally {
				setIsLoading( false );
			}
		};

		fetchMetaFields();
	}, [ postId ] );

	return (
		<>
			{ /* Select control for choosing a custom field */ }
			<SelectControl
				label={ __( 'Custom Field', 'spectra-pro' ) }
				value={ selectedMetaKey }
				options={ isLoading ? [ { label: __( 'Loading…', 'spectra-pro' ), value: '' } ] : metaKeys }
				onChange={ ( newValue ) => updateSetting( 'source.postCustomField', newValue ) }
			/>
			{ /* Text input for custom meta key when 'custom' is selected */ }
			{ selectedMetaKey === 'custom' && ! isLoading && (
				<TextControl
					label={ __( 'Custom Meta Key', 'spectra-pro' ) }
					value={ settings.source.postMetaKey || '' }
					onChange={ ( newValue ) => updateSetting( 'source.postMetaKey', newValue ) }
				/>
			) }
		</>
	);
};

export default MetaField;
