import "../InlineForm.css";
import { jsxs, jsx, Fragment } from "react/jsx-runtime";
import { Form } from "antd";
import React__default, { useState, useMemo, useEffect, useCallback } from "react";
import Button from "./Button.js";
import Icon from "./Icon.js";
import { useTheme } from "./Theme/UI.js";
import "./Theme/themeUtils.js";
import "./Theme/themes.js";
const formBase = "InlineForm_formBase_dc13d";
const buttonsContainer = "InlineForm_buttonsContainer_dc13d";
const formItemInput = "InlineForm_formItemInput_dc13d";
const readOnlyElement = "InlineForm_readOnlyElement_dc13d";
const css = {
  formBase,
  buttonsContainer,
  formItemInput,
  readOnlyElement
};
function InlineForm({
  label,
  children,
  valueFormatter,
  initialValue,
  value,
  isPassword = false,
  rules,
  required,
  testId = "",
  onSubmit,
  onEdit,
  onCancel,
  open,
  ...formProps
}) {
  const [isEditing, setIsEditing] = useState(false);
  const [hasFormError, setHasFormError] = useState(false);
  const [previousValue, setPreviousValue] = useState(initialValue);
  const [form] = Form.useForm();
  const shouldCollapseText = useMemo(() => String(initialValue).length >= 45, [initialValue]);
  const inputCurrentValue = Form.useWatch("input", form);
  const {
    themeSettings: { className: themeClass }
  } = useTheme();
  const classes = [css.formBase, themeClass];
  const readOnlyText = useMemo(() => {
    let textValue = valueFormatter ? valueFormatter(value ?? initialValue) : String(value ?? initialValue);
    if (value === void 0) {
      if (inputCurrentValue !== void 0 && inputCurrentValue !== initialValue)
        textValue = valueFormatter ? valueFormatter(inputCurrentValue) : inputCurrentValue;
    }
    if (isPassword)
      return textValue.replace(/\S/g, "*");
    if (shouldCollapseText)
      return textValue.slice(0, 50).concat("...");
    return textValue;
  }, [shouldCollapseText, value, initialValue, isPassword, inputCurrentValue, valueFormatter]);
  useEffect(() => {
    if (value !== void 0) {
      form.setFieldValue("input", value);
    } else {
      form.setFieldValue("input", initialValue);
    }
  }, [initialValue, value, form]);
  useEffect(() => {
    if (open !== void 0)
      setIsEditing(open);
  }, [open]);
  React__default.useEffect(() => {
    let mounted = true;
    if (isEditing) {
      (async () => {
        try {
          await form.validateFields(["input"]);
          if (mounted)
            setHasFormError(false);
        } catch {
          if (mounted)
            setHasFormError(true);
        }
      })();
    }
    return () => {
      mounted = false;
    };
  }, [inputCurrentValue, isEditing, form]);
  const handleEdit = useCallback(() => {
    if (open === void 0)
      setIsEditing(true);
    onEdit == null ? void 0 : onEdit();
  }, [open, onEdit]);
  const handleCancel = useCallback(() => {
    form.resetFields();
    form.setFieldValue("input", previousValue);
    if (open === void 0)
      setIsEditing(false);
    onCancel == null ? void 0 : onCancel();
  }, [open, onCancel, form, previousValue]);
  const handleConfirm = useCallback(async () => {
    if (form.getFieldError("input").length)
      return;
    form.submit();
    try {
      const formValues = await form.validateFields();
      setPreviousValue(formValues.input);
      if (open === void 0)
        setIsEditing(false);
      onSubmit == null ? void 0 : onSubmit(formValues.input);
    } catch (error) {
      form.setFieldValue("input", initialValue);
    }
  }, [form, initialValue, open, onSubmit]);
  return /* @__PURE__ */ jsxs(
    Form,
    {
      className: classes.join(" "),
      colon: false,
      form,
      layout: "inline",
      requiredMark: false,
      ...formProps,
      children: [
        /* @__PURE__ */ jsx("label", { children: label }),
        /* @__PURE__ */ jsx(
          Form.Item,
          {
            className: css.formItemInput,
            initialValue,
            name: "input",
            required,
            rules,
            validateTrigger: ["onSubmit", "onChange"],
            children: isEditing ? children : /* @__PURE__ */ jsx("span", { className: css.readOnlyElement, "data-testid": `value-${testId}`, children: readOnlyText })
          }
        ),
        /* @__PURE__ */ jsx("div", { className: css.buttonsContainer, children: isEditing ? /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsx(
            Button,
            {
              "data-testid": `submit-${testId}`,
              disabled: hasFormError,
              icon: /* @__PURE__ */ jsx(Icon, { name: "checkmark", title: "confirm" }),
              type: "primary",
              onClick: handleConfirm
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              "data-testid": `reset-${testId}`,
              icon: /* @__PURE__ */ jsx(Icon, { name: "close", size: "tiny", title: "cancel" }),
              type: "default",
              onClick: handleCancel
            }
          )
        ] }) : /* @__PURE__ */ jsx(
          Button,
          {
            "data-testid": `edit-${testId}`,
            icon: /* @__PURE__ */ jsx(Icon, { name: "pencil", size: "small", title: "Edit" }),
            type: "default",
            onClick: handleEdit
          }
        ) })
      ]
    }
  );
}
export {
  InlineForm as default
};
