/**
 * WordPress dependencies
 */
import { __ } from '@wordpress/i18n';
import { addFilter } from '@wordpress/hooks';
import { useState, useMemo, useEffect } from '@wordpress/element';
import { Flex, FlexItem, Tooltip, Icon } from '@wordpress/components';
import { help } from '@wordpress/icons';

/**
 * Internal dependencies
 */
import { hasOtherBlockAtts } from './../utils/index';
import { PWPSearchOption } from '../utils/search-options';

/**
 * Checks for Access Controls as part of the required PersonalizeWP logic.
 *
 * @param {Object} attributes All original PWP attributes
 * @return {Object} settings The updated array of attributes.
 */
const checkRequiredUserRoleAccessControl = ( required, attributes ) => {
	if (
		Object.hasOwn( attributes, 'userRoles' ) &&
		attributes.userRoles.length
	) {
		return true;
	}
	// Return original
	return required;
};
addFilter(
	'personalizeWP.hasRequiredFields',
	'personalizewp/check-for-user-role-access-control',
	checkRequiredUserRoleAccessControl
);

/**
 * Personalized Access Control - User Role Access
 *
 * @param {Object} props All the props passed to this function
 * @return {string} element component
 */
export default function UserRoleAccessControl( props ) {
	const { blockAtts, setPersonalizeWPAtts, settings } = props;

	const { userRoles = [] } = blockAtts;
	const ATTRIBUTE_KEY = 'userRoles';

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

	/** Functions **/
	const updateAttribute = ( key, value ) => {
		setPersonalizeWPAtts( {
			[ key ]: value,
		} );
	};

	const [ searchRole, setSearchRole ] = useState( '' );
	const wpUserRoles = settings.user_roles;

	/** Computed **/
	const displayRoles = useMemo( () => {
		if ( searchRole !== '' ) {
			return wpUserRoles.filter(
				( u ) =>
					u.label.toLowerCase().includes( searchRole ) ||
					u.value.toLowerCase().includes( searchRole )
			);
		}
		return wpUserRoles;
	}, [ wpUserRoles, searchRole ] );

	const selectedUserRoles = useMemo( () => {
		let mappedUserRoles = [];
		userRoles.forEach( ( pRole ) => {
			const role = wpUserRoles.find( ( r ) => r.value === pRole );
			if ( role ) {
				mappedUserRoles.push( role );
			}
		} );

		return mappedUserRoles;
	}, [ userRoles, wpUserRoles ] );

	return (
		<>
			<div className="pwp-panel user-role-fields">
				<Flex direction="row" align="flex-start">
					<FlexItem>
						<h3>
							{ __( 'User Role Access', 'personalizewp' ) }
						</h3>
					</FlexItem>
					<FlexItem>
						<Tooltip
							delay={ 200 }
							text={ __(
								'Choose which WordPress user roles have access to the content.',
								'personalizewp'
							) }
							className="pwp-tooltip"
							placement="bottom-end"
						>
							<div>
								<Icon icon={ help } size={ 20 } />
							</div>
						</Tooltip>
					</FlexItem>
				</Flex>

				<div className="user-role" key={ 'pwp-user-role' }>
					<PWPSearchOption
						label={ __( 'Search role', 'personalizewp' ) }
						placeholder={ __( 'Search role', 'personalizewp' ) }
						options={ displayRoles }
						selected={ selectedUserRoles }
						onChange={ ( options ) => {
							updateAttribute(
								ATTRIBUTE_KEY,
								options.map( ( o ) => o.value )
							);
						} }
						onInputChange={ ( input ) => {
							setSearchRole( input );
						} }
						disabled={ inertUserRoleAccessControl }
					/>
				</div>
			</div>
		</>
	);
}
