import React from "react"
import { BodyInputText } from "./style"

export interface NumberEditorProps {
    value: number
    onChange: (value: number) => void,
    onEditting: (editting: boolean) => void,
}

export const NumberEditor: React.FC<NumberEditorProps> = ({ value, onChange, onEditting }) => {
    const [currentInput, setCurrentInput] = React.useState<number>(value);
   
    const validate = (newValue: any, currentValue: any = null) => {
        const result = typeof newValue === 'string'
            ? !isNaN(Number(`${newValue}0`))
                ? newValue
                : currentValue
            : typeof newValue === 'boolean'
                ? newValue ? 1 : 0
                : newValue === 0 || (!!newValue && !isNaN(Number(newValue)))
                    ? Number(newValue)
                    : currentValue
        return result;
    }
    const handleChange = (event: any) => {
        const newValue = validate(event.target.value, currentInput);

        setCurrentInput(newValue)
        onChange(newValue)
    }

    return (
        <BodyInputText
            focused
            variant="standard"
            value={currentInput ? currentInput : ''}
            onChange={handleChange}
            onBlur={() => onEditting(false)}
            InputProps={{ autoFocus: true }} />
    )
}