import { ChangeEvent, useState } from "react";

interface NumberInputProps {
  min?: number;
  max?: number;
  step?: number;
  defaultValue?: number;
  onChange: (value: number) => void;
}

function NumberInput({
  min = 1,
  max = 100,
  step = 1,
  defaultValue = 1,
  onChange,
}: NumberInputProps) {
  const [value, setValue] = useState<number>(defaultValue);

  function handleChange(e: ChangeEvent<HTMLInputElement>) {
    let value = +e.target.value;

    if (value < min) value = min;
    if (value > max) value = max;

    setValue(value);
    onChange(value);
  }

  return (
    <input
      type="number"
      min={min}
      max={max}
      step={step}
      value={value}
      onChange={handleChange}
      className="px-3 py-2 rounded w-full outline-none"
    />
  );
}

export default NumberInput;
