/**
 * Inline product search used by the review step's "Assign…" action.
 */

import { useEffect, useState } from '@wordpress/element';
import { Button, Spinner, TextControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';

import { searchProducts } from '../api';

export default function ProductAssignPicker( { onSelect, onCancel } ) {
	const [ query, setQuery ] = useState( '' );
	const [ results, setResults ] = useState( [] );
	const [ isSearching, setIsSearching ] = useState( false );

	useEffect( () => {
		if ( query.trim().length < 2 ) {
			setResults( [] );
			return;
		}

		setIsSearching( true );

		const timeoutId = setTimeout( () => {
			searchProducts( query.trim() )
				.then( ( response ) => {
					setIsSearching( false );
					setResults( response.results );
				} )
				.catch( () => {
					setIsSearching( false );
					setResults( [] );
				} );
		}, 300 );

		return () => clearTimeout( timeoutId );
	}, [ query ] );

	return (
		<div className="embp-product-assign-picker">
			<TextControl
				placeholder={ __(
					'Search product name or SKU…',
					'emberprice'
				) }
				value={ query }
				onChange={ setQuery }
				__next40pxDefaultSize
				__nextHasNoMarginBottom
			/>

			{ isSearching && <Spinner /> }

			{ ! isSearching &&
				query.trim().length >= 2 &&
				0 === results.length && (
					<p>{ __( 'No products found.', 'emberprice' ) }</p>
				) }

			{ results.length > 0 && (
				<ul className="embp-product-assign-picker__results">
					{ results.map( ( result ) => (
						<li
							key={ `${ result.product_id }-${
								result.variation_id || 0
							}` }
						>
							<Button
								variant="tertiary"
								size="small"
								onClick={ () =>
									onSelect(
										result.product_id,
										result.variation_id
									)
								}
							>
								{ result.name }
								{ result.sku ? ` (${ result.sku })` : '' }
							</Button>
						</li>
					) ) }
				</ul>
			) }

			<Button variant="link" onClick={ onCancel }>
				{ __( 'Cancel', 'emberprice' ) }
			</Button>
		</div>
	);
}
