/**
 * External dependencies.
 */
import { SelectControl, TextControl } from '@wordpress/components';
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 an archive-related custom meta key.
 *
 * Displays a select control with available archive meta fields 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 archive field selection controls.
 */
const ArchiveField = ( { settings, updateSetting, type = 'text' } ) => {
	// State for loading status and available archive meta keys.
	const [ isLoading, setIsLoading ] = useState( true );
	const [ archiveMetaKeys, setArchiveMetaKeys ] = useState( [
		{ label: __( 'Choose', 'spectra-pro' ), value: '' },
		{ label: __( 'Custom Input', 'spectra-pro' ), value: 'custom' },
	] );

	// Extract the selected archive meta key from settings.
	const selectedArchiveMeta = settings.source.archiveMetaKey || '';

	// Initialize API client for fetching terms meta.
	const termsMetaAPI = new API( urls.termsMeta );

	// Fetch archive meta fields when the component mounts or dependencies change.
	useEffect( () => {
		/**
		 * Fetches available archive meta fields.
		 */
		const fetchArchiveFields = async () => {
			setIsLoading( true );

			try {
				// Fetch archive meta fields via API.
				const response = await termsMetaAPI.list( { type } );

				// Transform response data into select options.
				const fields = 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 fields.
				const options = [
					{ label: __( 'Choose', 'spectra-pro' ), value: '' },
					...fields,
					{ label: __( 'Custom Input', 'spectra-pro' ), value: 'custom' },
				];

				setArchiveMetaKeys( options );
			} catch ( error ) {
				setArchiveMetaKeys( [
					{ label: __( 'Choose', 'spectra-pro' ), value: '' },
					{ label: __( 'Custom Input', 'spectra-pro' ), value: 'custom' },
				] );
			} finally {
				setIsLoading( false );
			}
		};

		fetchArchiveFields();
	}, [ settings.source.type, settings.source.postId ] );

	return (
		<>
			{ /* Select control for choosing an archive custom field */ }
			<SelectControl
				label={ __( 'Custom Field', 'spectra-pro' ) }
				value={ selectedArchiveMeta }
				options={ isLoading ? [ { label: __( 'Loading…', 'spectra-pro' ), value: '' } ] : archiveMetaKeys }
				onChange={ ( newValue ) => updateSetting( 'source.archiveMetaKey', newValue ) }
				disabled={ isLoading }
			/>

			{ /* Text input for custom meta key when 'custom' is selected */ }
			{ selectedArchiveMeta === 'custom' && ! isLoading && (
				<TextControl
					label={ __( 'Custom Meta Key', 'spectra-pro' ) }
					value={ settings.source?.customArchiveMetaKey || '' }
					onChange={ ( newValue ) => updateSetting( 'source.customArchiveMetaKey', newValue ) }
					help={ __( 'Enter the meta key for the archive custom field', 'spectra-pro' ) }
				/>
			) }
		</>
	);
};

export default ArchiveField;
