import { React, PropTypes, classnames } from '@gravityforms/libraries';
import { getModules } from './utils';

const { forwardRef } = React;

/**
 * @module GridControls
 *
 * @description A component used to display controls for the data grid, such as search, filters, and bulk actions.
 *
 * @since 4.1.2
 *
 * @param {object}              props                   The component props.
 * @param {JSX.Element|null}    props.afterControlsLeft Element to render after the left controls content.
 * @param {Array}               props.modules           The modules for the data grid.
 * @param {object}              props.wrapperAttributes The attributes for the wrapper element.
 * @param {string|Array|object} props.wrapperClasses    The CSS classes for the wrapper element.
 * @param {object|null}         ref                     The ref object for this component.
 *
 * @return {JSX.Element} The GridControls component.
 */
const GridControls = forwardRef( ( props, ref ) => {
	const {
		afterControlsLeft = null,
		modules = [],
		wrapperAttributes = {},
		wrapperClasses = [],
	} = props;

	const {
		BulkActions,
		DateFilters,
		Search,
		SimpleFilters,
	} = getModules( modules, [ 'BulkActions', 'DateFilters', 'Search', 'SimpleFilters' ] );

	if ( ! BulkActions && ! DateFilters && ! SimpleFilters && ! Search && ! afterControlsLeft ) {
		return null;
	}

	const wrapperProps = {
		className: classnames( {
			'gform-data-grid__controls': true,
			'gform-data-grid__controls--has-bulk-actions': BulkActions,
			'gform-data-grid__controls--has-date-filters': DateFilters,
			'gform-data-grid__controls--has-search': Search,
			'gform-data-grid__controls--has-simple-filters': SimpleFilters,
		}, wrapperClasses ),
		...wrapperAttributes,
	};

	return (
		<div { ...wrapperProps } ref={ ref }>
			{ ( BulkActions || afterControlsLeft ) && (
				<div className="gform-data-grid__controls-inner gform-data-grid__controls-inner--left">
					{ BulkActions && <BulkActions.BulkActions { ...props } /> }
					{ afterControlsLeft }
				</div>
			) }
			{ ( Search || SimpleFilters || DateFilters ) && (
				<div className="gform-data-grid__controls-inner gform-data-grid__controls-inner--right">
					{ Search && <Search.Search { ...props } /> }
					{ SimpleFilters && <SimpleFilters.SimpleFilters { ...props } /> }
					{ DateFilters && <DateFilters.DateFilters { ...props } /> }
				</div>
			) }
		</div>
	);
} );

GridControls.propTypes = {
	afterControlsLeft: PropTypes.element,
	modules: PropTypes.array,
	wrapperAttributes: PropTypes.object,
	wrapperClasses: PropTypes.oneOfType( [
		PropTypes.string,
		PropTypes.array,
		PropTypes.object,
	] ),
};

GridControls.displayName = 'GridControls';

export default GridControls;
