import {useState, useRef} from '@wordpress/element';
import {__} from '@wordpress/i18n';
import './TokenInput.scss';

const TokenInput = ( {tokens, onChange, placeholder, className = ''} ) => {
	const [inputValue, setInputValue] = useState( '' );
	const containerRef = useRef( null );

	const handleRemoveTag = ( tagToRemove ) => {
		onChange( tokens.filter( tag => tag !== tagToRemove ) );
	};

	const handleAddTag = ( newTag ) => {
		const trimmedTag = newTag.trim();
		// Only add the tag if it's empty and doesn't already exist
		if ( trimmedTag && !tokens.includes( trimmedTag ) ) {
			onChange( [...tokens, trimmedTag] );
		}
		setInputValue( '' ); // Reset the input field after adding a new tag.
	};

	const handleKeyDown = ( e ) => {
		if ( e.key === 'Enter' ) {
			e.preventDefault();
			handleAddTag( inputValue );
		}
	};

	return (
		<div className="adpresso-token-input" ref={containerRef}>
			<div className="adpresso-token-input__control">
				{tokens.map( tag => (
					<span key={tag} className={`adpresso-token-input__token ${className}`}>
						{tag}
						<button
							type="button"
							className="adpresso-token-input__token-remove"
							onClick={() => handleRemoveTag( tag )}>
							&times;
					</button>
					</span>
				) )}
				<input
					type="text"
					className="adpresso-token-input__input"
					value={inputValue}
					onChange={( e ) => setInputValue( e.target.value )}
					onKeyDown={handleKeyDown}
					placeholder={tokens.length === 0 ? placeholder : ''}
				/>
			</div>
			{inputValue && (
				<ul className="adpresso-token-input__dropdown">
					<li
						className="adpresso-token-input__option"
						onClick={() => handleAddTag( inputValue )}
					>
						{__( 'Add', 'adpresso' )} "<strong>{inputValue}</strong>"
					</li>
				</ul>
			)}
		</div>
	);
};

export default TokenInput;
