import React, { useCallback, useState } from 'react';
import PropTypes from 'prop-types';
import { reactDebounce } from '@QPUtils/helper';
import './styles.scss';

const propTypes = {
	placeholder: PropTypes.string,
	onSearchHandler: PropTypes.func,
	defaultValue: PropTypes.string,
};

export default function Search( {
	placeholder = 'Search...',
	defaultValue = '',
	onSearchHandler = () => {},
	custom = '',
} ) {
	const [ searchText, setSearchText ] = useState( defaultValue );

	const classNames = [ 'quizpress-search-component', custom && `${ custom }` ]
		.filter( Boolean )
		.join( ' ' );

	const debouncedAPICall = useCallback(
		reactDebounce( ( keyword ) => {
			onSearchHandler( keyword );
		}, 1000 ),
		[ onSearchHandler ]
	);

	const searchHandler = ( searchValue ) => {
		setSearchText( searchValue );
		debouncedAPICall( searchValue );
	};

	const handleClear = () => {
		if ( searchText ) {
			setSearchText( '' );
			onSearchHandler( '' );
		}
	};

	return (
		<React.Fragment>
			<div className={ classNames }>
				<span className="quizpress-search-component__search quizpress-icon quizpress-icon--search" />
				<input
					id="search"
					type="text"
					className="quizpress-search-component__input quizpress-input"
					placeholder={ placeholder }
					value={ searchText }
					onChange={ ( e ) => searchHandler( e.target.value ) }
				/>
				{ searchText && (
					<button
						onClick={ handleClear }
						className="quizpress-search-component__control"
					>
						<span className="quizpress-icon quizpress-icon--close-small"></span>
					</button>
				) }
			</div>
		</React.Fragment>
	);
}

Search.propTypes = propTypes;
