import React, { useState, useEffect } from "react";
import { Input as AntInput } from "antd";
import { useDebounce } from "use-debounce";
import { useObserver } from "mobx-react";
import { useStores } from "client/hooks/useStores";
import runEffects from "client/tools/runEffects";

const Input = ({ placeholder, sourceValueName, getValue, Effects }) => {
  const { calculationStore } = useStores();
  const [currentValue, setCurrentValue] = useState(undefined);
  const [debouncedValue] = useDebounce(currentValue, 800);

  useEffect(() => {
    if (sourceValueName) {
      setCurrentValue(calculationStore.getValue(sourceValueName));
    }
  }, [sourceValueName]);

  useEffect(() => {
    if (sourceValueName) {
      if (debouncedValue) {
        calculationStore.setValue(sourceValueName, debouncedValue);
        runEffects(Effects, calculationStore);
      }
    }
  }, [debouncedValue]);

  return useObserver(() => (
    <AntInput
      placeholder={placeholder}
      value={sourceValueName ? currentValue : getValue(calculationStore)}
      onChange={(e) => {
        setCurrentValue(e.target.value);
      }}
    />
  ));
};

export default Input;
