/**
 * External dependencies.
 */
import { ToggleControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies.
 */
import CustomSelectControl from '@spectra-pro-components/CustomSelectControl';
import { LINK_SOURCES } from '@spectra-pro-extensions/dynamic-content/utils/constants';
import LinkAuthorInfoField from '@spectra-pro-extensions/dynamic-content/components/Fields/LinkAuthorInfoField';
import LinkPostMetaField from '@spectra-pro-extensions/dynamic-content/components/Fields/LinkPostMetaField';

/**
 * Renders controls for enabling and configuring dynamic link settings.
 *
 * Displays a toggle to enable/disable dynamic links and, when enabled, a select control
 * for choosing the link source. Conditionally renders additional fields for specific
 * link sources (e.g., custom field, author info).
 *
 * @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 dynamic link configuration controls.
 */
const EnableLinkControl = ( { settings, updateSetting } ) => (
	<>
		{ /* Toggle control to enable/disable dynamic links */ }
		<ToggleControl
			__nextHasNoMarginBottom
			__next40pxDefaultSize
			label={ __( 'Enable Link', 'spectra-pro' ) }
			checked={ settings.enableLink }
			onChange={ ( newValue ) => {
				updateSetting( 'enableLink', newValue );

				// Set default link source if enabling and none is set.
				if ( newValue ) {
					updateSetting( 'linkSource', settings.linkSource || 'post_permalink' );
				}
			} }
		/>
		{ /* Link source selection when dynamic link is enabled */ }
		{ settings.enableLink && (
			<>
				<CustomSelectControl
					label={ __( 'Link Source', 'spectra-pro' ) }
					value={ settings.linkSource }
					options={ LINK_SOURCES }
					onChange={ ( newValue ) => updateSetting( 'linkSource', newValue ) }
				/>

				{ /* Custom field configuration for custom_field link source */ }
				{ settings.linkSource === 'custom_field' && (
					<LinkPostMetaField settings={ settings } updateSetting={ updateSetting } type="url" />
				) }

				{ /* Author info configuration for author_info link source */ }
				{ settings.linkSource === 'author_info' && (
					<LinkAuthorInfoField settings={ settings } updateSetting={ updateSetting } type="url" />
				) }
			</>
		) }
	</>
);

export default EnableLinkControl;
