/**
 * ProductSearchControl — a combobox that searches Goose Commerce products
 * via the REST API and lets the user pick one by name.
 */
import { useState, useEffect } from '@wordpress/element';
import { ComboboxControl } from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';

export default function ProductSearchControl( { value, onChange, label } ) {
	const [ options, setOptions ] = useState( [] );
	const [ isLoading, setIsLoading ] = useState( false );

	// Load initial product list (or the currently selected product).
	useEffect( () => {
		fetchProducts( '' );
	}, [] );

	// If a value is set but not in the list, fetch it directly.
	useEffect( () => {
		if ( value && ! options.find( ( o ) => o.value === value ) ) {
			apiFetch( { path: `/ggmc/v1/products/${ value }` } )
				.then( ( product ) => {
					setOptions( ( prev ) => {
						if ( prev.find( ( o ) => o.value === product.id ) ) {
							return prev;
						}
						return [
							{
								value: product.id,
								label: product.sku
									? `${ product.name } (${ product.sku })`
									: product.name,
							},
							...prev,
						];
					} );
				} )
				.catch( () => {} );
		}
	}, [ value ] );

	function fetchProducts( search ) {
		setIsLoading( true );
		const path = search
			? `/ggmc/v1/products/search?q=${ encodeURIComponent( search ) }`
			: '/ggmc/v1/products/search';

		apiFetch( { path } )
			.then( ( products ) => {
				setOptions(
					products.map( ( p ) => ( {
						value: p.id,
						label: p.sku
							? `${ p.name } (${ p.sku })`
							: p.name,
					} ) )
				);
			} )
			.catch( () => setOptions( [] ) )
			.finally( () => setIsLoading( false ) );
	}

	return (
		<ComboboxControl
			label={ label || 'Product' }
			value={ value }
			options={ options }
			onChange={ onChange }
			onFilterValueChange={ ( input ) => fetchProducts( input ) }
			__nextHasNoMarginBottom
		/>
	);
}
