/**
 * WordPress dependencies
 */
import { __ } from '@wordpress/i18n';
import { applyFilters } from '@wordpress/hooks';
import { SelectControl, Flex, Tooltip, Icon } from '@wordpress/components';
import { useState } from "@wordpress/element";
import { help } from '@wordpress/icons';

/**
 * Internal dependencies
 */
import { hasOtherBlockAtts, isEmpty } from './../utils/index';

/**
 * Render the Integrations controls.
 *
 * @since 3.1.0
 * @param {Object} props All the props passed to this function
 */
export default function IntegrationsControls( props ) {
	const { blockAtts, setPersonalizeWPAtts, settings } = props;

	if ( isEmpty( settings?.integrations?.plugins ) ) {
		return null;
	}

	// Process the segments into options we can use.
	const integrationOptions = [
		{
			value: '',
			label: __( '-- Select a plugin --', 'personalizewp' ),
		},
	].concat( ...Array.from( settings.integrations.plugins ) );

	const [ integrationsPlugin, setIntegrationsPlugin ] = useState( blockAtts?.integrations?.plugin ?? '' );

	/**
	 * Update plugin options.
	 *
	 * @param {Object} integrationsOptions integrations options to update.
	 */
	const updatePluginOptions = ( integrationsOptions ) => {
		let integrations;

		if ( ! isEmpty( integrationsOptions ) ) {
			integrations = Object.assign(
				{
					plugin: integrationsPlugin,
				},
				{ ...integrationsOptions }
			);
		}

		setPersonalizeWPAtts( { integrations } );
	};

	/**
	 * Update plugin value.
	 *
	 * @param {String} value plugin value.
	 */
	const setIntegrationsPluginOption = ( value ) => {
		setIntegrationsPlugin( value );
		setPersonalizeWPAtts( { integrations: undefined } );
	}

	// These controls can be marked as inert if settings have been made elsewhere.
	const inert = hasOtherBlockAtts( blockAtts, [ 'integrations' ] );

	return (
		<div className="pwp-panel integrations">
			<Flex direction="row" align="flex-start">
				<h3>{ __( 'Integrations', 'personalizewp' ) }</h3>
				<Tooltip
					delay={ 200 }
					text={ __(
						'This will return true depending on what additional options you select within the supported integration.',
						'personalizewp'
					) }
					className="pwp-tooltip"
					placement="bottom-end"
				>
					<div>
						<Icon icon={ help } size={ 20 } />
					</div>
				</Tooltip>
			</Flex>
			<SelectControl
				label={ __( 'Plugin', 'personalizewp' ) }
				hideLabelFromVision={ true }
				value={ integrationsPlugin }
				options={ integrationOptions }
				onChange={ ( value ) => {
						setIntegrationsPluginOption( value );
					}
				}
				disabled={ inert }
				__nextHasNoMarginBottom
			/>
			{!inert && !!integrationsPlugin && (
				<div className="pwp-panel integrations-fields">
					{ applyFilters(
						'personalizeWP.additionalIntegrationsControls',
						null,
						props,
						integrationsPlugin,
						updatePluginOptions
					) }
				</div>
			)}
		</div>
	);
}
