import BigNumber from 'bignumber.js';
import React from 'react';
import { useEffect } from 'react';
import {useState} from 'react';
import { toSuffixFormat } from '../../utils/configureFormats';

interface IProps {
  value: string;
  onChange: (v: string) => boolean;
}

export function EditableValue(props: IProps) {
  const [currentValue, setCurrentValue] = useState(props.value || "");
  const [isEditMode, setIsEditMode] = useState(false);
  const inputRef = React.useRef<any>();

  useEffect(() => {
    setCurrentValue(props.value);
  }, [props.value]);

  useEffect(() => {
    if (isEditMode && inputRef.current) {
      inputRef.current.focus();
    }
  }, [isEditMode]);

  const valueChanged = (e: any) => setCurrentValue(e.currentTarget?.value || "");

  const valueAccepted = () => {
    props.onChange(currentValue);

    setCurrentValue(props.value);
    setIsEditMode(false);
  }

  const valueRejected = () => {
    setCurrentValue(props.value);
    setIsEditMode(false);
  }

  const handleKeyDown = (e: any) => {
    if (e.key === 'Enter') {
      valueAccepted();

      e.stopPropagation();
    }

    if (e.key === 'Escape') {
      valueRejected();

      e.stopPropagation();
    }
  }

  return <>
    {
      !isEditMode &&
      <span>
        <span>{toSuffixFormat(new BigNumber(currentValue), undefined)}</span> <a onClick={() => setIsEditMode(true)}>(edit)</a>
      </span>
    }
    {
      isEditMode &&
      <span>
        <input ref={inputRef} type='text' value={currentValue} onBlur={valueRejected} onChange={valueChanged} onKeyDown={handleKeyDown}></input>
        <span onMouseDown={valueAccepted}>✔️</span>
        <span onClick={valueRejected}>✖️</span>
      </span>
    }
    </>;
}