/**
 * 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 configuring taxonomy and term separator.
 *
 * Displays a select control for choosing a taxonomy and a text input for specifying a
 * separator for terms. Updates the dynamic content settings with the selected taxonomy
 * and separator.
 *
 * @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 terms configuration controls.
 */
const TermsField = ( { settings, updateSetting } ) => {
	// State for loading status and available taxonomy options.
	const [ isLoading, setIsLoading ] = useState( true );
	const [ taxonomyOptions, setTaxonomyOptions ] = useState( [
		{ label: __( 'Loading…', 'spectra-pro' ), value: '' },
	] );

	// Initialize API client for fetching terms.
	const termsAPI = new API( urls.terms );

	// Fetch available taxonomies when the component mounts.
	useEffect( () => {
		/**
		 * Fetches available taxonomies.
		 */
		const fetchTaxonomies = async () => {
			setIsLoading( true );

			try {
				// Fetch taxonomies via API.
				const response = await termsAPI.list();

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

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

		fetchTaxonomies();
	}, [] );

	// Set default taxonomy and separator values on mount.
	useEffect( () => {
		updateSetting( 'source.taxonomyType', settings.source?.taxonomyType || 'category' );
		updateSetting( 'source.taxonomyValueSeparator', settings.source?.taxonomyValueSeparator || ',' );
	}, [] );

	return (
		<>
			{ /* Select control for choosing a taxonomy */ }
			<SelectControl
				label={ __( 'Taxonomy', 'spectra-pro' ) }
				value={ settings.source?.taxonomyType || '' }
				options={ isLoading ? [ { label: __( 'Loading…', 'spectra-pro' ), value: '' } ] : taxonomyOptions }
				onChange={ ( value ) => updateSetting( 'source.taxonomyType', value ) }
			/>

			{ /* Text input for term separator when a taxonomy is selected */ }
			{ settings.source?.taxonomyType && (
				<TextControl
					label={ __( 'Separator', 'spectra-pro' ) }
					value={ settings.source?.taxonomyValueSeparator || '' }
					onChange={ ( value ) => updateSetting( 'source.taxonomyValueSeparator', value ) }
					help={ __( 'Separator between taxonomy terms', 'spectra-pro' ) }
				/>
			) }
		</>
	);
};

export default TermsField;
