import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
import { css } from '@emotion/css';
import { debounce } from 'lodash';
import * as React from 'react';
import { useRef, useCallback, useMemo } from 'react';
import '@grafana/data';
import { useStyles2 } from '../../themes/ThemeContext.js';
import 'micro-memoize';
import '@emotion/react';
import 'tinycolor2';
import '../../utils/skeleton.js';
import { Field } from '../Forms/Field.js';
import { InlineToast } from '../InlineToast/InlineToast.js';
import { EllipsisAnimated } from './EllipsisAnimated.js';

const SHOW_SUCCESS_DURATION = 2 * 1e3;
function AutoSaveField(props) {
  const {
    invalid,
    loading,
    onFinishChange,
    saveErrorMessage = "Error saving this value",
    error,
    children,
    disabled,
    ...restProps
  } = props;
  const [fieldState, setFieldState] = React.useState({
    isLoading: false,
    showSuccess: false,
    showError: invalid
  });
  const fieldRef = useRef(null);
  React.useEffect(() => {
    let timeoutId;
    if (fieldState.showSuccess) {
      const time = fieldState.showError ? 0 : SHOW_SUCCESS_DURATION;
      timeoutId = setTimeout(() => {
        setFieldState({ ...fieldState, showSuccess: false });
      }, time);
    }
    return () => {
      window.clearTimeout(timeoutId);
    };
  }, [fieldState]);
  const handleChange = useCallback(
    (nextValue) => {
      if (invalid) {
        return;
      }
      setFieldState({ ...fieldState, isLoading: true, showSuccess: false });
      onFinishChange(nextValue).then(() => {
        setFieldState({
          isLoading: false,
          showSuccess: true,
          showError: false
        });
      }).catch(() => {
        setFieldState({
          ...fieldState,
          isLoading: false,
          showError: true
        });
      });
    },
    [invalid, fieldState, onFinishChange]
  );
  const lodashDebounce = useMemo(() => debounce(handleChange, 600, { leading: false }), [handleChange]);
  const isInvalid = invalid || fieldState.showError || void 0;
  const styles = useStyles2(getStyles);
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      Field,
      {
        ...restProps,
        loading: loading || void 0,
        invalid: isInvalid,
        disabled,
        error: error || fieldState.showError && saveErrorMessage,
        ref: fieldRef,
        className: styles.widthFitContent,
        children: React.cloneElement(
          children((newValue) => {
            lodashDebounce(newValue);
          })
        )
      }
    ),
    fieldState.isLoading && /* @__PURE__ */ jsxs(InlineToast, { referenceElement: fieldRef.current, placement: "right", children: [
      "Saving ",
      /* @__PURE__ */ jsx(EllipsisAnimated, {})
    ] }),
    fieldState.showSuccess && /* @__PURE__ */ jsx(InlineToast, { suffixIcon: "check", referenceElement: fieldRef.current, placement: "right", children: "Saved!" })
  ] });
}
AutoSaveField.displayName = "AutoSaveField";
const getStyles = () => {
  return {
    widthFitContent: css({
      width: "fit-content"
    })
  };
};

export { AutoSaveField };
//# sourceMappingURL=AutoSaveField.js.map
