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;
  error?: string;
  emptyError?: boolean;
  value: string;
  sx?: SxProps<Theme>;
  min?: number;
  max?: number;
}

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

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

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