/**
 * 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';
import { useWPService } from '../utils/wp-service';

/**
 * 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 checkRequiredSpecificUserAccessControl = ( required, attributes ) => {
	if ( Object.hasOwn( attributes, 'users' ) && attributes.users.length ) {
		return true;
	}
	// Return original
	return required;
};
addFilter(
	'personalizeWP.hasRequiredFields',
	'personalizewp/check-for-specific-user-access-control',
	checkRequiredSpecificUserAccessControl
);

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

	const { users = [] } = blockAtts;

	const ATTRIBUTE_KEY = 'users';
	const DEFAULT_PAGE = 1;
	// State variable for the input text on the search control
	const [ searchUser, setSearchUser ] = useState( '' );
	// State variable for the selected users as an object { value, label }
	const [ selectedUsers, setSelectedUsers ] = useState( [] );
	// State variable for the list of WP users from the user endpoint
	const [ userOptions, setUsers ] = useState( [] );
	const [ currentPage, setCurrentPage ] = useState( DEFAULT_PAGE );
	const [ totalPages, setTotalPages ] = useState( DEFAULT_PAGE );

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

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

	/** Hooks **/
	const { fetchUsers } = useWPService();

	/** Effects **/
	useEffect( () => {
		const callUserEndpoint = async () => {
			if ( searchUser !== '' ) {
				const wpUsers = await fetchUsers( {
					searchText: searchUser,
					currentPage,
				} );
				if ( wpUsers ) {
					const { data, totalPages } = wpUsers;
					const u = data.map( ( { name, id } ) => ( {
						label: name,
						value: id,
					} ) );
					if ( currentPage === DEFAULT_PAGE ) {
						setTotalPages( totalPages );
						setUsers( u );
					} else {
						setUsers( [ ...userOptions, ...u ] );
					}
				}
			}
		};
		callUserEndpoint();
	}, [ searchUser, currentPage ] );

	// This side effect will trigger only once when the component is loaded
	// Here we populate the selected display users into an array of object from the selected users of string of array
	// We call the user endpoint with passing an include of the list of users id we need
	useEffect( () => {
		const callUserEndpointForSelected = async () => {
			const wpUsers = await fetchUsers( {
				includeUsers: users,
				perPage: users.length,
			} );
			if ( wpUsers ) {
				const { data } = wpUsers;
				setSelectedUsers(
					data.map( ( { name, id } ) => ( {
						label: name,
						value: id,
					} ) )
				);
			}
		};

		if ( users.length > 0 ) {
			callUserEndpointForSelected();
		}
	}, [] );

	return (
		<>
			<div className="pwp-panel user-fields">
				<Flex direction="row" align="flex-start">
					<FlexItem>
						<h3>
							{ __(
								'Specific User Access',
								'personalizewp'
							) }
						</h3>
					</FlexItem>
					<FlexItem>
						<Tooltip
							delay={ 200 }
							text={ __(
								'Show block content to one or more specific WordPress users.',
								'personalizewp'
							) }
							className="pwp-tooltip"
							placement="bottom-end"
						>
							<div>
								<Icon icon={ help } size={ 20 } />
							</div>
						</Tooltip>
					</FlexItem>
				</Flex>

				<div className="user-access" key={ 'pwp-user-role' }>
					<PWPSearchOption
						label={ __( 'Search for user', 'personalizewp' ) }
						placeholder={ __( 'Search for user', 'personalizewp' ) }
						options={ userOptions }
						totalPages={ totalPages }
						currentPage={ currentPage }
						selected={ selectedUsers }
						onChange={ ( options ) => {
							setSelectedUsers( options );
							updateAttribute(
								ATTRIBUTE_KEY,
								options.map( ( o ) => o.value )
							);
						} }
						onInputChange={ ( input ) => {
							setCurrentPage( DEFAULT_PAGE );
							setSearchUser( input );
						} }
						onLoadMore={ () => setCurrentPage( currentPage + 1 ) }
						disabled={ inertSpecificUserAccessControl }
					/>
				</div>
			</div>
		</>
	);
}
