import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
import { useField, useFormikContext } from 'formik';
import { isNotNil, omit } from 'ramda';
import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
import { forwardRef, useState, useRef, useEffect } from 'react';
import classnames from 'classnames';
import { isNotEmpty, noop } from '@bigbinary/neeto-cist';
import useOnClickOutside from '@bigbinary/neeto-commons-frontend/react-utils/useOnClickOutside';
import useStateWithDependency from '@bigbinary/neeto-commons-frontend/react-utils/useStateWithDependency';
import useHotkeys from '@bigbinary/neeto-hotkeys';
import Check from '@bigbinary/neeto-icons/Check';
import Close from '@bigbinary/neeto-icons/Close';
import Button from '@bigbinary/neetoui/Button';
import Input from '@bigbinary/neetoui/Input';
import { t } from 'i18next';
import { n } from './inject-css-C2dztUxs.js';
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';

var TOOLTIP_PROPS = {
  save: {
    content: t("neetoMolecules.common.actions.save"),
    position: "top",
    delay: 300
  },
  cancel: {
    content: t("neetoMolecules.common.actions.cancel"),
    position: "top",
    delay: 300
  }
};

var css = ".neeto-molecules-autosave-input input::-webkit-inner-spin-button,.neeto-molecules-autosave-input input::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}.neeto-molecules-autosave-input input[type=number]{-moz-appearance:textfield}.neeto-molecules-autosave-input .neeto-ui-input__suffix{align-items:stretch!important;margin-right:0!important;padding-bottom:0!important;padding-top:0!important}.neeto-molecules-autosave-input .neeto-ui-input__suffix .neeto-ui-btn{padding-bottom:0!important;padding-top:0!important}";
n(css,{});

var mergeRefs = function mergeRefs() {
  for (var _len = arguments.length, refs = new Array(_len), _key = 0; _key < _len; _key++) {
    refs[_key] = arguments[_key];
  }
  return function (node) {
    return refs.forEach(function (ref) {
      return typeof ref === "function" ? ref(node) : ref.current = node;
    });
  };
};

var _excluded$1 = ["saveOnBlur", "clearOnSave", "nullable", "value", "isSaving", "className", "handleSubmit", "handleCancel", "submitButtonProps", "cancelButtonProps", "dirty", "onInlineInputBlur", "size"];
function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = false, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = true, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), true), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
var InlineInput = /*#__PURE__*/forwardRef(function (props, ref) {
  var _props$saveOnBlur = props.saveOnBlur,
    saveOnBlur = _props$saveOnBlur === void 0 ? false : _props$saveOnBlur,
    _props$clearOnSave = props.clearOnSave,
    clearOnSave = _props$clearOnSave === void 0 ? false : _props$clearOnSave,
    _props$nullable = props.nullable,
    nullable = _props$nullable === void 0 ? false : _props$nullable,
    _props$value = props.value,
    value = _props$value === void 0 ? "" : _props$value,
    isSaving = props.isSaving,
    _props$className = props.className,
    className = _props$className === void 0 ? "" : _props$className,
    _props$handleSubmit = props.handleSubmit,
    handleSubmit = _props$handleSubmit === void 0 ? noop : _props$handleSubmit,
    _props$handleCancel = props.handleCancel,
    handleCancel = _props$handleCancel === void 0 ? noop : _props$handleCancel,
    _props$submitButtonPr = props.submitButtonProps,
    submitButtonProps = _props$submitButtonPr === void 0 ? {} : _props$submitButtonPr,
    _props$cancelButtonPr = props.cancelButtonProps,
    cancelButtonProps = _props$cancelButtonPr === void 0 ? {} : _props$cancelButtonPr,
    dirty = props.dirty,
    _props$onInlineInputB = props.onInlineInputBlur,
    onInlineInputBlur = _props$onInlineInputB === void 0 ? noop : _props$onInlineInputB,
    _props$size = props.size,
    size = _props$size === void 0 ? "medium" : _props$size,
    otherProps = _objectWithoutProperties(props, _excluded$1);
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isSubmitting = _useState2[0],
    setIsSubmitting = _useState2[1];
  var _useStateWithDependen = useStateWithDependency(value !== null && value !== void 0 ? value : ""),
    _useStateWithDependen2 = _slicedToArray(_useStateWithDependen, 2),
    internalValue = _useStateWithDependen2[0],
    setInternalValue = _useStateWithDependen2[1];
  var inputRef = useRef(null);
  var inputWrapperRef = useRef(null);
  var trimmedValue = internalValue && (internalValue === null || internalValue === void 0 ? void 0 : internalValue.trim());
  var isValidValue = nullable || isNotEmpty(trimmedValue) && isNotNil(trimmedValue);
  var isDirty = internalValue !== value || dirty;
  var handleFocusOut = function handleFocusOut() {
    if (!isValidValue || isSubmitting) return;
    onInlineInputBlur(trimmedValue);
    if (saveOnBlur && isDirty) {
      onSubmit();
      return;
    }
    onCancel();
  };
  useOnClickOutside(inputWrapperRef, handleFocusOut);
  var onSubmit = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
      return _regenerator().w(function (_context) {
        while (1) switch (_context.p = _context.n) {
          case 0:
            setIsSubmitting(true);
            _context.p = 1;
            _context.n = 2;
            return handleSubmit(trimmedValue);
          case 2:
            clearOnSave && setInternalValue("");
          case 3:
            _context.p = 3;
            setIsSubmitting(false);
            return _context.f(3);
          case 4:
            return _context.a(2);
        }
      }, _callee, null, [[1,, 3, 4]]);
    }));
    return function onSubmit() {
      return _ref.apply(this, arguments);
    };
  }();
  var onCancel = function onCancel() {
    handleCancel(trimmedValue);
  };
  var closeRef = useHotkeys("escape", function (event) {
    event.stopPropagation();
    onCancel();
  }, {
    mode: "scoped"
  });
  var submitRef = useHotkeys(["command+return", "return"], function () {
    return onSubmit();
  }, {
    mode: "scoped",
    enabled: isValidValue
  });
  useEffect(function () {
    return inputRef.current && inputRef.current.focus();
  }, [isSubmitting]);
  return /*#__PURE__*/jsx("div", {
    className: classnames("flex flex-grow", _defineProperty({}, className, className)),
    ref: inputWrapperRef,
    children: /*#__PURE__*/jsx(Input, _objectSpread$1(_objectSpread$1({
      size: size,
      disableTrimOnBlur: true,
      className: "neeto-molecules-autosave-input",
      "data-testid": "neeto-molecules-autosave-input",
      disabled: isSubmitting,
      ref: mergeRefs(inputRef, closeRef, submitRef),
      value: internalValue
    }, otherProps), {}, {
      suffix: /*#__PURE__*/jsxs(Fragment, {
        children: [/*#__PURE__*/jsx(Button, _objectSpread$1(_objectSpread$1({
          size: size,
          "data-testid": "neeto-molecules-autosave-input-save",
          icon: Check,
          loading: isSubmitting || isSaving,
          style: "text",
          tabIndex: -1,
          tooltipProps: TOOLTIP_PROPS["save"],
          onClick: onSubmit
        }, submitButtonProps), {}, {
          disabled: !isValidValue || isSubmitting || isSaving || submitButtonProps.disabled || !isDirty
        })), /*#__PURE__*/jsx(Button, _objectSpread$1(_objectSpread$1({
          ref: ref,
          size: size,
          "data-testid": "neeto-molecules-autosave-input-cancel",
          icon: Close,
          style: "text",
          tabIndex: -1,
          tooltipProps: TOOLTIP_PROPS["cancel"],
          onClick: onCancel
        }, cancelButtonProps), {}, {
          disabled: isSubmitting || isSaving || cancelButtonProps.disabled
        }))]
      }),
      onChange: function onChange(e) {
        var _otherProps$onChange;
        otherProps === null || otherProps === void 0 || (_otherProps$onChange = otherProps.onChange) === null || _otherProps$onChange === void 0 || _otherProps$onChange.call(otherProps, e);
        setInternalValue(e.target.value);
      }
    }))
  });
});
InlineInput.displayName = "InlineInput";

var _excluded = ["name"];
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var FormikInlineInput = function FormikInlineInput(_ref) {
  var name = _ref.name,
    props = _objectWithoutProperties(_ref, _excluded);
  var _useField = useField(name),
    _useField2 = _slicedToArray(_useField, 3),
    field = _useField2[0],
    meta = _useField2[1],
    _useField2$ = _useField2[2],
    setValue = _useField2$.setValue,
    setTouched = _useField2$.setTouched;
  var _useFormikContext = useFormikContext(),
    submitForm = _useFormikContext.submitForm,
    isSubmitting = _useFormikContext.isSubmitting,
    resetForm = _useFormikContext.resetForm,
    dirty = _useFormikContext.dirty;
  var handleSubmit = function handleSubmit(value) {
    var _props$handleSubmit;
    setValue(value);
    (_props$handleSubmit = props.handleSubmit) === null || _props$handleSubmit === void 0 || _props$handleSubmit.call(props, value);
    return submitForm();
  };
  return /*#__PURE__*/jsx(InlineInput, _objectSpread(_objectSpread(_objectSpread({
    error: meta.touched ? meta.error : "",
    isSaving: isSubmitting
  }, props), {}, {
    handleCancel: function handleCancel() {
      var _props$handleCancel;
      resetForm();
      (_props$handleCancel = props.handleCancel) === null || _props$handleCancel === void 0 || _props$handleCancel.call(props);
    }
  }, _objectSpread(_objectSpread({
    handleSubmit: handleSubmit
  }, omit(["onBlur"], field)), {}, {
    dirty: dirty
  })), {}, {
    onInlineInputBlur: function onInlineInputBlur(trimmedValue) {
      setValue(trimmedValue);
      setTouched(true);
    }
  }));
};

export { FormikInlineInput, InlineInput };
//# sourceMappingURL=InlineInput.js.map
