import React, { useState } from 'react';
import {
  Button,
  Spinner,
} from '../../components/ui/Widget';

interface IProps {
  submitCallBack: (value: string) => Promise<boolean>;
  initialValue: string;
  buttonTitle: string;
  onFinish: (status: boolean) => void;
}

export function NumericValueSubmit(props: IProps) {
  const [isLoading, setLoading] = useState(false);
  const [value, setValue] = useState(props.initialValue ?? '');

  async function handleSubmit() {
    try {
      setLoading(true);

      const result = await props.submitCallBack(value);

      if (result) {
        props.onFinish(true);
      }
    } catch (e) {
      console.error(e);
    }

    setLoading(false);
  }

  function handleChange(e: any) {
    const { value } = e.currentTarget;

    if (!isNaN(+value)) {
      setValue(value);
    }
  }

  return (
    <div className={'wizard-step-container'}>
      {isLoading && (
        <div className="spinner-container">
          <Spinner />{' '}
        </div>
      )}

      <input type="text" onChange={handleChange} value={value} />

      <Button onClick={handleSubmit} color="#ff975b" background={'#fff'}>
        {props.buttonTitle ?? 'Submit'}
      </Button>
    </div>
  );
}
