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

const { forwardRef } = React;

/**
 * @module GridEmpty
 * @description The empty state for the DataGrid component.
 *
 * @since 4.3.0
 *
 * @param {object}              props                        Component props.
 * @param {Array}               props.data                   The data for the grid.
 * @param {JSX.Element}         props.EmptyImage             The image to display when the grid is empty.
 * @param {object}              props.emptyMessageAttributes Custom attributes for the empty message.
 * @param {string|Array|object} props.emptyMessageClasses    Custom classes for the empty message.
 * @param {object}              props.i18n                   The i18n object.
 * @param {Array}               props.modules                The modules to use.
 * @param {object}              props.moduleState            The module state.
 * @param {object|null}         ref                          Ref to the component.
 *
 * @return {JSX.Element} The GridEmpty component.
 */
const GridEmpty = forwardRef( ( props, ref ) => {
	const {
		data = [],
		EmptyImage = null,
		emptyMessageAttributes = {},
		emptyMessageClasses = [],
		i18n = {},
		modules = [],
		moduleState = {},
	} = props;
	const {
		emptyTitleI18n = '',
		emptyMessageI18n = '',
	} = i18n;

	if ( data.length !== 0 ) {
		return null;
	}

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

	if ( Search && moduleState?.searchActive ) {
		return <Search.NoResults { ...props } />;
	}

	const emptyProps = {
		className: classnames( {
			'gform-data-grid__no-data-message': true,
		}, emptyMessageClasses ),
		...emptyMessageAttributes,
	};

	return ! moduleState?.searchActive && ( EmptyImage || emptyMessageI18n || emptyTitleI18n ) && (
		<div { ...emptyProps } ref={ ref }>
			{ EmptyImage && <EmptyImage /> }
			{ emptyTitleI18n && <Text size="text-md" weight="medium" spacing={ [ 5, 0, 0, 0 ] }>{ emptyTitleI18n }</Text> }
			{ emptyMessageI18n && <Text size="text-sm" spacing={ [ 3, 0, 0, 0 ] }>{ emptyMessageI18n }</Text> }
		</div>
	);
} );

GridEmpty.propTypes = {
	data: PropTypes.array,
	EmptyImage: PropTypes.oneOfType( [
		PropTypes.node,
		PropTypes.func,
		PropTypes.object,
	] ),
	emptyMessageAttributes: PropTypes.object,
	emptyMessageClasses: PropTypes.oneOfType( [
		PropTypes.string,
		PropTypes.array,
		PropTypes.object,
	] ),
	i18n: PropTypes.object,
	modules: PropTypes.array,
	moduleState: PropTypes.object,
};

GridEmpty.displayName = 'GridEmpty';

export default GridEmpty;
