import CustomTextField from "./CustomTextField";

import type { ChangeEvent, KeyboardEvent, FocusEvent } from "react";
import type { SxProps, Theme } from "@mui/material";

interface CustomNumberFieldProps {
  placeholder: string;
  onChange?: (event: ChangeEvent<HTMLInputElement>) => void;
  onKeyDown?: (event: KeyboardEvent<HTMLInputElement>) => void;
  onBlur?: (event: FocusEvent<HTMLInputElement>) => void;
  value: string;
  sx?: SxProps<Theme>;
  min?: number;
  max?: number;
}

export default function CustomNumberField({
  placeholder,
  value,
  sx,
  onChange,
  onKeyDown,
  onBlur,
  min = -999999999,
  max = 999999999,
}: CustomNumberFieldProps) {
  const onInputChange = (event: ChangeEvent<HTMLInputElement>) => {
    const inputValue = event.target.value;

    if (
      Number(inputValue) >= min &&
      Number(inputValue) <= max &&
      (inputValue === "" ||
        inputValue.match(/^\d*$/) ||
        (inputValue[0] === "-" && inputValue.slice(1).match(/^\d*$/)))
    ) {
      onChange?.({ ...event, target: { ...event.target, value: inputValue } });
    }
  };

  return (
    <CustomTextField
      placeholder={placeholder}
      sx={sx}
      onChange={onInputChange}
      onKeyDown={onKeyDown}
      onBlur={onBlur}
      value={value}
    />
  );
}
