import React from "react";
import { TextInput } from "./TextInput";
import { TextFieldVariants } from "@mui/material";

enum InputState {
  Normal,
  StartNeg,
  StartDecimal,
}

export function AmountInput(p: {
  label?: string;
  editable: boolean;
  placeholder: string;
  style?: React.CSSProperties;
  value: number;
  onValueChange: (val: number) => void;
  variant?: TextFieldVariants;
}): React.ReactElement {
  const [state, setState] = React.useState(InputState.Normal);

  let value = "";

  if (state === InputState.StartNeg) {
    value = "-";
  } else if (state === InputState.StartDecimal) {
    value = String(p.value) + ".";
  } else if (!Number.isNaN(p.value) && p.value !== 0) {
    value = String(p.value);
  }

  return (
    <TextInput
      {...p}
      value={value}
      onValueChange={(a) => {
        if (a === "-") {
          setState(InputState.StartNeg);
          return;
        }

        if (a?.endsWith(".")) {
          setState(InputState.StartDecimal);
        } else if (state !== InputState.Normal) {
          setState(InputState.Normal);
        }
        const parsed = Number(a);

        // Empty field
        if (a?.length === 0 || a === undefined) p.onValueChange(NaN);
        // Input number
        else if (a.length > 0 && !Number.isNaN(parsed)) p.onValueChange(parsed);
      }}
    />
  );
}
