import { useState } from '@wordpress/element';
import { CheckboxControl, TextControl } from '@wordpress/components';

function PerPageMaxInput( { value, onCommit } ) {
	const [ draft, setDraft ] = useState( String( value ) );

	function handleBlur() {
		const clamped = Math.min( 50, Math.max( 1, parseInt( draft, 10 ) || 50 ) );
		setDraft( String( clamped ) );
		onCommit( clamped );
	}

	return (
		<TextControl
			label="Maximum allowed value"
			type="number"
			min="1"
			max="50"
			value={ draft }
			onChange={ setDraft }
			onBlur={ handleBlur }
		/>
	);
}

export default function FilterSelector( { available, selected, onChange } ) {
	function toggleFilter( key ) {
		const updated = { ...selected };
		if ( updated[ key ] ) {
			delete updated[ key ];
		} else {
			updated[ key ] = { enabled: true, description: available[ key ]?.description || '' };
		}
		onChange( updated );
	}

	function updateFilterConfig( key, partial ) {
		const updated = {
			...selected,
			[ key ]: { ...selected[ key ], ...partial },
		};
		onChange( updated );
	}

	return (
		<div className="aic-filter-selector">
			<p className="aic-selector-hint">
				Select which query filters the AI can use when calling this tool.
			</p>
			{ Object.entries( available ).map( ( [ key, filterDef ] ) => {
				const isEnabled = !! selected[ key ]?.enabled;

				return (
					<div key={ key } className="aic-filter-item">
						<CheckboxControl
							label={ `${ key } (${ filterDef.type })` }
							help={ filterDef.description }
							checked={ isEnabled }
							onChange={ () => toggleFilter( key ) }
						/>

						{ isEnabled && (
							<div className="aic-filter-config">
								<TextControl
									label="Custom description for AI"
									value={ selected[ key ]?.description || '' }
									onChange={ ( val ) => updateFilterConfig( key, { description: val } ) }
									placeholder={ filterDef.description }
								/>

								{ key === 'per_page' && (
									<PerPageMaxInput
										value={ selected[ key ]?.max || 50 }
										onCommit={ ( val ) => updateFilterConfig( key, { max: val } ) }
									/>
								) }
							</div>
						) }
					</div>
				);
			} ) }
		</div>
	);
}
