import _extends from "@babel/runtime/helpers/esm/extends";
import React, { forwardRef, useCallback, useEffect, useRef, useState } from "react";
import classNames from "classnames";
import { EditableContent } from "../EditableContent/EditableContent";
export const EditableText = /*#__PURE__*/forwardRef((_ref, ref) => {
  let {
    onSave,
    onCancel,
    value,
    inputProps,
    allowEmptyString,
    ...props
  } = _ref;
  const [currentValue, setCurrentValue] = useState(value);
  const [prevValue, setPrevValue] = useState(value);
  const escapeRef = useRef(false);
  useEffect(() => {
    if (currentValue !== value) {
      setCurrentValue(value);
      setPrevValue(value);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [value]);
  const handleBlur = useCallback(e => {
    if (escapeRef.current) {
      setCurrentValue(prevValue);
      escapeRef.current = false;
    } else {
      if (e.target.value.trim().length > 0 && prevValue !== e.target.value) {
        setPrevValue(e.target.value);
        setCurrentValue(e.target.value);
        typeof onSave === "function" && onSave(e);
      } else {
        !allowEmptyString ? setCurrentValue(prevValue) : typeof onSave === "function" && prevValue !== e.target.value && onSave(e);
      }
    }
  }, [allowEmptyString, onSave, prevValue]);
  const handleKeyDown = useCallback(e => {
    if (e.key === "Enter") {
      e.target.blur();
    }
    if (e.key === "Escape") {
      escapeRef.current = true;
      e.target.blur();
      typeof onCancel === "function" && onCancel();
    }
  }, [onCancel]);
  const handleChange = useCallback(e => {
    setCurrentValue(e.target.value);
  }, []);
  return /*#__PURE__*/React.createElement(EditableContent, _extends({}, props, {
    ref: ref,
    inputProps: {
      ...inputProps,
      value: currentValue != null ? currentValue : "",
      onBlur: handleBlur,
      onKeyDown: handleKeyDown,
      onChange: handleChange,
      type: "text",
      className: classNames("c-input", inputProps == null ? void 0 : inputProps.className)
    }
  }));
});
EditableText.displayName = "EditableText";
//# sourceMappingURL=EditableText.js.map