/**
 * External dependencies
 */
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import DebouncedRangeControl from '@spectra-components/debounced-range-control';

/**
 * Minimum allowed value for posts per page.
 *
 * @type {number}
 */
const MIN_POSTS_PER_PAGE = 1;

/**
 * Maximum allowed value for posts per page.
 *
 * @type {number}
 */
const MAX_POSTS_PER_PAGE = 100;

/**
 * A control component for setting the number of posts per page in a query.
 *
 * This component renders a range slider allowing users to specify how many posts
 * to display per page in the query results. The value is constrained between
 * `MIN_POSTS_PER_PAGE` (1) and `MAX_POSTS_PER_PAGE` (100). When a valid value is
 * selected, it updates the query via the provided `onChange` callback, preserving
 * the current offset.
 *
 * @param {Object}   props            The component props.
 * @param {number}   props.perPage    The current number of posts per page.
 * @param {number}   [props.offset=0] The current offset value. Defaults to 0.
 * @param {Function} props.onChange   Callback function to update the perPage and offset values in the query.
 * @return {Element} The rendered DebouncedRangeControl component.
 */
const PerPageControl = ( { perPage, offset = 0, onChange } ) => {
	return (
		<DebouncedRangeControl
			__next40pxDefaultSize
			__nextHasNoMarginBottom
			label={ __( 'Items per page', 'spectra-pro' ) }
			min={ MIN_POSTS_PER_PAGE }
			max={ MAX_POSTS_PER_PAGE }
			onChange={ ( newPerPage ) => {
				// Validate the new value to ensure it's a number within the allowed range.
				if (
					isNaN( newPerPage ) ||
					newPerPage < MIN_POSTS_PER_PAGE ||
					newPerPage > MAX_POSTS_PER_PAGE
				) {
					return;
				}
				// Update the query with the new perPage value and preserve the current offset.
				onChange( { perPage: newPerPage, offset } );
			} }
			value={ parseInt( perPage, 10 ) }
		/>
	);
};

export default PerPageControl;
