'use client';

import IconButton from '@mui/material/IconButton';
import AddIcon from '@mui/icons-material/Add';
import RemoveIcon from '@mui/icons-material/Remove';
import { QuantityField, QuantityControl } from '../styles';

interface Props {
	value: number;
	max: number;
	label?: string;
	onChange: (value: number) => void;
}

function clamp(value: number, max: number) {
	return Math.min(Math.max(value, 1), Math.max(max, 1));
}

export default function QuantitySelector({ value, max, label = 'Cantidad', onChange }: Props) {
	return (
		<QuantityField>
			<span>{label}</span>
			<QuantityControl>
				<IconButton
					size="small"
					aria-label="Disminuir cantidad"
					onClick={() => onChange(clamp(value - 1, max))}
				>
					<RemoveIcon fontSize="small" />
				</IconButton>
				<strong>{value}</strong>
				<IconButton
					size="small"
					aria-label="Aumentar cantidad"
					onClick={() => onChange(clamp(value + 1, max))}
				>
					<AddIcon fontSize="small" />
				</IconButton>
			</QuantityControl>
		</QuantityField>
	);
}
