import { SelectControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { DATA_SOURCES } from '@spectra-pro-extensions/dynamic-content/utils/constants';

/**
 * Renders a select control for choosing a data source for dynamic content.
 *
 * Allows users to select a data source (e.g., Current Post, Site) and updates the
 * dynamic content settings with the selected source and an appropriate default 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 data source select control.
 */
const DataSourceField = ( { settings, updateSetting } ) => (
	<SelectControl
		__next40pxDefaultSize
		__nextHasNoMarginBottom
		label={ __( 'Data Source', 'spectra-pro' ) }
		value={ settings.source.type }
		options={ DATA_SOURCES }
		onChange={ ( newValue ) => {
			// Update the source type in settings.
			updateSetting( 'source.type', newValue );

			// Set default field based on selected source.
			switch ( newValue ) {
				case 'post_type':
				case 'current_post':
					updateSetting( 'source.field', 'post_title' );
					break;
				case 'request_parameter':
					updateSetting( 'source.field', 'GET' );
					break;
				case 'current_user':
					updateSetting( 'source.field', 'display_name' );
					break;
				case 'site':
					updateSetting( 'source.field', 'site_title' );
					break;
				case 'archive':
					updateSetting( 'source.field', 'archive_title' );
					break;
				default:
					updateSetting( 'source.field', '' );
			}
		} }
	/>
);

export default DataSourceField;
