/* eslint-disable react-hooks/exhaustive-deps */
import { ChangeEvent, useState } from "react";

interface Props {
  readOnly?: boolean;
  defaultValue?: string | number;
  min?: number;
  max?: number;
  onlyNumbers?: boolean;
  className?: string;
  value: string | number;
  onChange: (value: string | number) => void;
}

function Input({
  readOnly,
  min = 0,
  max = 100,
  onlyNumbers,
  className,
  value,
  onChange,
}: Props) {
  const [, setValue] = useState<string | number | undefined>(value);

  function handleChange(e: ChangeEvent<HTMLInputElement>) {
    if (onlyNumbers) {
      if (!isNaN(+e.target.value)) {
        if (+e.target.value < min || +e.target.value > max) return;
        setValue(+e.target.value);
        onChange(+e.target.value);
      }
    } else {
      setValue(e.target.value);
      onChange(e.target.value);
    }
  }

  return (
    <input
      readOnly={readOnly}
      type="text"
      className={`px-3 py-3.5 text-sm text-[#0D1922] rounded-lg w-full outline-none ${className}`}
      value={value}
      onChange={handleChange}
    />
  );
}

export default Input;
