import { Text, UseInput } from "./Ink";
import React, { useState } from "react";

type NumberInputProps = {
  onValidation: (value: number) => void;

  useInput: UseInput;
};

export const NumberInput = ({ onValidation, useInput }: NumberInputProps) => {
  const [value, setValue] = useState(0);

  useInput((input, key) => {
    if (key.return) {
      onValidation(value);
    } else if (key.delete) {
      const valueAsString = `${value}`;
      setValue(
        Number(
          valueAsString.length === 1
            ? 0
            : valueAsString.slice(0, valueAsString.length - 1),
        ),
      );
    } else if (key.upArrow) {
      setValue(value + 1);
    } else if (key.downArrow) {
      setValue(value - 1);
    } else {
      const newRawValue = Number(`${value}` + input);
      setValue(isNaN(newRawValue) ? value : newRawValue);
    }
  });

  return <Text>{value}</Text>;
};
