import { useState } from "react";
import classes from "./classes.module.scss";
import { MinusIcon, PlusIcon } from "@heroicons/react/24/outline";

type IProps = {
	defaultValue: number;
	onChange: (value: number) => void;
	min?: number;
	max?: number;
	disabled?: boolean;
};

export default function NumberPicker(props: IProps) {
	const { defaultValue, onChange, min, max, disabled } = props;
	const [value, setValue] = useState(defaultValue);

	const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
		let value = parseInt(e.target.value);
		if (isNaN(value)) value = 1;
		if (min && value < min) value = min;
		if (max && value > max) value = max;

		setValue(value);
		onChange(value);
	};

	const handleMinus = () => {
		handleChange({ target: { value: value - 1 } } as any);
	};

	const handlePlus = () => {
		handleChange({ target: { value: value + 1 } } as any);
	};

	return (
		<div className={classes["root"]}>
			<button onClick={handleMinus} disabled={min && value <= min ? true : false} className={classes["button"]}>
				<MinusIcon width="20" height="20" />
			</button>
			<input type="number" value={value} onChange={handleChange} disabled={disabled} className={classes["input"]} />
			<button onClick={handlePlus} disabled={max && value >= max ? true : false} className={classes["button"]}>
				<PlusIcon width="20" height="20" />
			</button>
		</div>
	);
}
