import { StyleSheet, TextInput } from "react-native";

export type NumberInputProps = {
  defaultValue: number;
  onValueSet: (value: number) => any;
  label?: string;
};

export function NumberInput({
  defaultValue,
  onValueSet,
  label,
}: NumberInputProps) {
  const defValue = Number.isNaN(defaultValue) ? 0 : defaultValue;

  function doOnValueSet(value: string) {
    const iVal = parseFloat(value) || parseInt(value);
    onValueSet && onValueSet(iVal);
  }

  const sDefValue = new String(defValue).valueOf();

  return (
    <TextInput
      clearTextOnFocus={true}
      defaultValue={sDefValue}
      onChangeText={doOnValueSet}
      inputMode="decimal"
      style={styles.numberInput}
      aria-label={label || "Enter measurement"}
    />
  );
}

const styles = StyleSheet.create({
  inputWrapper: {
    alignItems: "flex-start",
    flexDirection: "row",
    verticalAlign: "middle",
  },
  unitHints: {
    padding: 10,
    fontSize: 20,
    verticalAlign: "middle",
  },
  numberInput: {
    borderWidth: 1,
    borderRadius: 4,
    borderColor: "grey",
    padding: 4,
    margin: 4,
    fontSize: 25,
  },
});
