"use strict";
const jsxRuntime = require("react/jsx-runtime");
const React = require("react");
const designSystem = require("@strapi/design-system");
const helperPlugin = require("@strapi/helper-plugin");
const reactQuery = require("react-query");
const reactRouterDom = require("react-router-dom");
const useContentTypes = require("./useContentTypes-7da293cc.js");
const Icons = require("@strapi/icons");
const formik = require("formik");
const PropTypes = require("prop-types");
const reactIntl = require("react-intl");
const index = require("./index-3649838b.js");
const styled = require("styled-components");
const yup = require("yup");
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
function _interopNamespace(e) {
  if (e && e.__esModule)
    return e;
  const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
  if (e) {
    for (const k in e) {
      if (k !== "default") {
        const d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: () => e[k]
        });
      }
    }
  }
  n.default = e;
  return Object.freeze(n);
}
const React__namespace = /* @__PURE__ */ _interopNamespace(React);
const PropTypes__default = /* @__PURE__ */ _interopDefault(PropTypes);
const styled__default = /* @__PURE__ */ _interopDefault(styled);
const yup__namespace = /* @__PURE__ */ _interopNamespace(yup);
const formatValue = (value) => value.reduce((acc, curr) => {
  const key = curr.split(".")[0];
  if (!acc[key]) {
    acc[key] = [];
  }
  acc[key].push(curr);
  return acc;
}, {});
const StyledTable = styled__default.default(designSystem.RawTable)`
  tbody tr:nth-child(odd) {
    background: ${({ theme }) => theme.colors.neutral100};
  }

  thead th span {
    color: ${({ theme }) => theme.colors.neutral500};
  }

  td,
  th {
    padding-block-start: ${({ theme }) => theme.spaces[3]};
    padding-block-end: ${({ theme }) => theme.spaces[3]};
    width: 10%;
    vertical-align: middle;
    text-align: center;
  }

  tbody tr td:first-child {
    /**
     * Add padding to the start of the first column to avoid the checkbox appearing
     * too close to the edge of the table
     */
    padding-inline-start: ${({ theme }) => theme.spaces[2]};
  }
`;
const getCEHeaders = (isDraftAndPublish) => {
  const headers = [
    { id: "Settings.webhooks.events.create", defaultMessage: "Create" },
    { id: "Settings.webhooks.events.update", defaultMessage: "Update" },
    { id: "app.utils.delete", defaultMessage: "Delete" }
  ];
  if (isDraftAndPublish) {
    headers.push({ id: "app.utils.publish", defaultMessage: "Publish" });
    headers.push({ id: "app.utils.unpublish", defaultMessage: "Unpublish" });
  }
  return headers;
};
const getCEEvents = (isDraftAndPublish) => {
  const entryEvents = ["entry.create", "entry.update", "entry.delete"];
  if (isDraftAndPublish) {
    entryEvents.push("entry.publish", "entry.unpublish");
  }
  return {
    entry: entryEvents,
    media: ["media.create", "media.update", "media.delete"]
  };
};
const WebhookEventContext = React__namespace.createContext();
const Root = ({ children }) => {
  const { formatMessage } = reactIntl.useIntl();
  const { collectionTypes, isLoading } = useContentTypes.useContentTypes();
  const isDraftAndPublish = React__namespace.useMemo(
    () => collectionTypes.some((ct) => ct.options.draftAndPublish === true),
    [collectionTypes]
  );
  const label = formatMessage({
    id: "Settings.webhooks.form.events",
    defaultMessage: "Events"
  });
  return /* @__PURE__ */ jsxRuntime.jsx(WebhookEventContext.Provider, { value: { isDraftAndPublish }, children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 1, children: [
    /* @__PURE__ */ jsxRuntime.jsx(designSystem.FieldLabel, { "aria-hidden": true, children: label }),
    isLoading && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Loader, { children: formatMessage({
      id: "Settings.webhooks.events.isLoading",
      defaultMessage: "Events loading"
    }) }),
    /* @__PURE__ */ jsxRuntime.jsx(StyledTable, { "aria-label": label, children })
  ] }) });
};
Root.propTypes = {
  children: PropTypes__default.default.oneOfType([PropTypes__default.default.arrayOf(PropTypes__default.default.node), PropTypes__default.default.node]).isRequired
};
const Headers = ({ getHeaders = getCEHeaders }) => {
  const { isDraftAndPublish } = React__namespace.useContext(WebhookEventContext);
  const { formatMessage } = reactIntl.useIntl();
  const headers = getHeaders(isDraftAndPublish);
  return /* @__PURE__ */ jsxRuntime.jsx(designSystem.RawThead, { children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.RawTr, { children: [
    /* @__PURE__ */ jsxRuntime.jsx(designSystem.RawTh, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.VisuallyHidden, { children: formatMessage({
      id: "Settings.webhooks.event.select",
      defaultMessage: "Select event"
    }) }) }),
    headers.map((header) => {
      if (["app.utils.publish", "app.utils.unpublish"].includes(header.id)) {
        return /* @__PURE__ */ jsxRuntime.jsx(
          designSystem.RawTh,
          {
            title: formatMessage({
              id: "Settings.webhooks.event.publish-tooltip",
              defaultMessage: "This event only exists for content with draft & publish enabled"
            }),
            children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", children: formatMessage(header) })
          },
          header.id
        );
      }
      return /* @__PURE__ */ jsxRuntime.jsx(designSystem.RawTh, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", children: formatMessage(header) }) }, header.id);
    })
  ] }) });
};
Headers.defaultProps = {
  getHeaders: getCEHeaders
};
Headers.propTypes = {
  getHeaders: PropTypes__default.default.func
};
const Body = ({ providedEvents }) => {
  const { isDraftAndPublish } = React__namespace.useContext(WebhookEventContext);
  const events = providedEvents || getCEEvents(isDraftAndPublish);
  const { values, handleChange: onChange } = formik.useFormikContext();
  const inputName = "events";
  const inputValue = values.events;
  const disabledEvents = [];
  const formattedValue = formatValue(inputValue);
  const handleSelect = ({ target: { name, value } }) => {
    let set = new Set(inputValue);
    if (value) {
      set.add(name);
    } else {
      set.delete(name);
    }
    onChange({ target: { name: inputName, value: Array.from(set) } });
  };
  const handleSelectAll = ({ target: { name, value } }) => {
    let set = new Set(inputValue);
    if (value) {
      events[name].forEach((event) => {
        if (!disabledEvents.includes(event)) {
          set.add(event);
        }
      });
    } else {
      events[name].forEach((event) => set.delete(event));
    }
    onChange({ target: { name: inputName, value: Array.from(set) } });
  };
  return /* @__PURE__ */ jsxRuntime.jsx(designSystem.RawTbody, { children: Object.entries(events).map(([event, value]) => {
    return /* @__PURE__ */ jsxRuntime.jsx(
      EventRow,
      {
        disabledEvents,
        name: event,
        events: value,
        inputValue: formattedValue[event],
        handleSelect,
        handleSelectAll
      },
      event
    );
  }) });
};
Body.defaultProps = {
  providedEvents: null
};
Body.propTypes = {
  providedEvents: PropTypes__default.default.object
};
const removeHyphensAndTitleCase = (str) => str.replace(/-/g, " ").split(" ").map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(" ");
const EventRow = ({ disabledEvents, name, events, inputValue, handleSelect, handleSelectAll }) => {
  const { formatMessage } = reactIntl.useIntl();
  const enabledCheckboxes = events.filter((event) => !disabledEvents.includes(event));
  const hasSomeCheckboxSelected = inputValue.length > 0;
  const areAllCheckboxesSelected = inputValue.length === enabledCheckboxes.length;
  const onChangeAll = ({ target: { name: name2 } }) => {
    const valueToSet = !areAllCheckboxesSelected;
    handleSelectAll({
      target: { name: name2, value: valueToSet }
    });
  };
  const targetColumns = 5;
  return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.RawTr, { children: [
    /* @__PURE__ */ jsxRuntime.jsx(designSystem.RawTd, { children: /* @__PURE__ */ jsxRuntime.jsx(
      designSystem.Checkbox,
      {
        indeterminate: hasSomeCheckboxSelected && !areAllCheckboxesSelected,
        "aria-label": formatMessage({
          id: "global.select-all-entries",
          defaultMessage: "Select all entries"
        }),
        name,
        onChange: onChangeAll,
        value: areAllCheckboxesSelected,
        children: removeHyphensAndTitleCase(name)
      }
    ) }),
    events.map((event) => {
      return /* @__PURE__ */ jsxRuntime.jsx(designSystem.RawTd, { children: /* @__PURE__ */ jsxRuntime.jsx(
        designSystem.BaseCheckbox,
        {
          disabled: disabledEvents.includes(event),
          "aria-label": event,
          name: event,
          value: inputValue.includes(event),
          onValueChange: (value) => handleSelect({ target: { name: event, value } })
        }
      ) }, event);
    }),
    events.length < targetColumns && /* @__PURE__ */ jsxRuntime.jsx(designSystem.RawTd, { colSpan: targetColumns - events.length })
  ] });
};
EventRow.defaultProps = {
  disabledEvents: [],
  events: [],
  inputValue: [],
  handleSelect() {
  },
  handleSelectAll() {
  }
};
EventRow.propTypes = {
  disabledEvents: PropTypes__default.default.array,
  events: PropTypes__default.default.array,
  inputValue: PropTypes__default.default.array,
  handleSelect: PropTypes__default.default.func,
  handleSelectAll: PropTypes__default.default.func,
  name: PropTypes__default.default.string.isRequired
};
const EventTable = { Root, Headers, Body, EventRow };
function EventTableCE() {
  return /* @__PURE__ */ jsxRuntime.jsxs(EventTable.Root, { children: [
    /* @__PURE__ */ jsxRuntime.jsx(EventTable.Headers, {}),
    /* @__PURE__ */ jsxRuntime.jsx(EventTable.Body, {})
  ] });
}
const HTTP_HEADERS = [
  "A-IM",
  "Accept",
  "Accept-Charset",
  "Accept-Encoding",
  "Accept-Language",
  "Accept-Datetime",
  "Access-Control-Request-Method",
  "Access-Control-Request-Headers",
  "Authorization",
  "Cache-Control",
  "Connection",
  "Content-Length",
  "Content-Type",
  "Cookie",
  "Date",
  "Expect",
  "Forwarded",
  "From",
  "Host",
  "If-Match",
  "If-Modified-Since",
  "If-None-Match",
  "If-Range",
  "If-Unmodified-Since",
  "Max-Forwards",
  "Origin",
  "Pragma",
  "Proxy-Authorization",
  "Range",
  "Referer",
  "TE",
  "User-Agent",
  "Upgrade",
  "Via",
  "Warning"
];
const Combobox = ({ name, onChange, value, ...props }) => {
  const {
    values: { headers }
  } = formik.useFormikContext();
  const [options, setOptions] = React.useState(HTTP_HEADERS);
  React.useEffect(() => {
    setOptions(
      HTTP_HEADERS.filter(
        (key) => !headers?.some((header) => header.key !== value && header.key === key)
      )
    );
  }, [headers, value]);
  const handleChange = (value2) => {
    onChange({ target: { name, value: value2 } });
  };
  const handleCreateOption = (value2) => {
    setOptions((prev) => [...prev, value2]);
    handleChange(value2);
  };
  return /* @__PURE__ */ jsxRuntime.jsx(
    designSystem.CreatableCombobox,
    {
      ...props,
      onClear: () => handleChange(""),
      onChange: handleChange,
      onCreateOption: handleCreateOption,
      placeholder: "",
      value,
      children: options.map((key) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.ComboboxOption, { value: key, children: key }, key))
    }
  );
};
Combobox.defaultProps = {
  value: void 0
};
Combobox.propTypes = {
  name: PropTypes__default.default.string.isRequired,
  onChange: PropTypes__default.default.func.isRequired,
  value: PropTypes__default.default.string
};
const HeadersInput = () => {
  const { formatMessage } = reactIntl.useIntl();
  const { values, errors } = formik.useFormikContext();
  return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 1, children: [
    /* @__PURE__ */ jsxRuntime.jsx(designSystem.FieldLabel, { children: formatMessage({
      id: "Settings.webhooks.form.headers",
      defaultMessage: "Headers"
    }) }),
    /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { padding: 8, background: "neutral100", hasRadius: true, children: /* @__PURE__ */ jsxRuntime.jsx(
      formik.FieldArray,
      {
        validateOnChange: false,
        name: "headers",
        render: ({ push, remove }) => /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Grid, { gap: 4, children: [
          values.headers.map((header, index2) => (
            // eslint-disable-next-line
            /* @__PURE__ */ jsxRuntime.jsxs(React__namespace.default.Fragment, { children: [
              /* @__PURE__ */ jsxRuntime.jsx(designSystem.GridItem, { col: 6, children: /* @__PURE__ */ jsxRuntime.jsx(
                formik.Field,
                {
                  as: Combobox,
                  name: `headers.${index2}.key`,
                  "aria-label": `row ${index2 + 1} key`,
                  label: formatMessage({
                    id: "Settings.webhooks.key",
                    defaultMessage: "Key"
                  }),
                  error: errors.headers?.[index2]?.key && errors.headers[index2].key
                }
              ) }),
              /* @__PURE__ */ jsxRuntime.jsx(designSystem.GridItem, { col: 6, children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { alignItems: "flex-end", children: [
                /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { style: { flex: 1 }, children: /* @__PURE__ */ jsxRuntime.jsx(
                  formik.Field,
                  {
                    as: designSystem.TextInput,
                    name: `headers.${index2}.value`,
                    "aria-label": `row ${index2 + 1} value`,
                    label: formatMessage({
                      id: "Settings.webhooks.value",
                      defaultMessage: "Value"
                    }),
                    error: errors.headers?.[index2]?.value && errors.headers[index2].value
                  }
                ) }),
                /* @__PURE__ */ jsxRuntime.jsx(
                  designSystem.Flex,
                  {
                    paddingLeft: 2,
                    style: { alignSelf: "center" },
                    paddingTop: errors.headers?.[index2]?.value ? 0 : 5,
                    children: /* @__PURE__ */ jsxRuntime.jsx(
                      helperPlugin.RemoveRoundedButton,
                      {
                        disabled: values.headers.length === 1,
                        onClick: () => remove(index2),
                        label: formatMessage(
                          {
                            id: "Settings.webhooks.headers.remove",
                            defaultMessage: "Remove header row {number}"
                          },
                          { number: index2 + 1 }
                        )
                      }
                    )
                  }
                )
              ] }) })
            ] }, `${index2}.${header.key}`)
          )),
          /* @__PURE__ */ jsxRuntime.jsx(designSystem.GridItem, { col: 12, children: /* @__PURE__ */ jsxRuntime.jsx(
            designSystem.TextButton,
            {
              type: "button",
              onClick: () => {
                push({ key: "", value: "" });
              },
              startIcon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Plus, {}),
              children: formatMessage({
                id: "Settings.webhooks.create.header",
                defaultMessage: "Create new header"
              })
            }
          ) })
        ] })
      }
    ) })
  ] });
};
const Icon = styled__default.default.svg(
  ({ theme, color }) => `
  width: ${12 / 16}rem;
  height: ${12 / 16}rem;

  path {
    fill: ${theme.colors[color]};
  }
`
);
const Status = ({ isPending, statusCode }) => {
  const { formatMessage } = reactIntl.useIntl();
  if (isPending) {
    return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, alignItems: "center", children: [
      /* @__PURE__ */ jsxRuntime.jsx(Icon, { as: Icons.Loader }),
      /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { children: formatMessage({ id: "Settings.webhooks.trigger.pending", defaultMessage: "pending" }) })
    ] });
  }
  if (statusCode >= 200 && statusCode < 300) {
    return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, alignItems: "center", children: [
      /* @__PURE__ */ jsxRuntime.jsx(Icon, { as: Icons.Check, color: "success700" }),
      /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { children: formatMessage({ id: "Settings.webhooks.trigger.success", defaultMessage: "success" }) })
    ] });
  }
  if (statusCode >= 300) {
    return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, alignItems: "center", children: [
      /* @__PURE__ */ jsxRuntime.jsx(Icon, { as: Icons.Cross, color: "danger700" }),
      /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { children: [
        formatMessage({ id: "Settings.error", defaultMessage: "error" }),
        " ",
        statusCode
      ] })
    ] });
  }
  return null;
};
Status.propTypes = {
  isPending: PropTypes__default.default.bool.isRequired,
  statusCode: PropTypes__default.default.number
};
Status.defaultProps = {
  statusCode: void 0
};
const Message = ({ statusCode, message }) => {
  const { formatMessage } = reactIntl.useIntl();
  if (statusCode >= 200 && statusCode < 300) {
    return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { justifyContent: "flex-end", children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { textColor: "neutral600", ellipsis: true, children: formatMessage({
      id: "Settings.webhooks.trigger.success.label",
      defaultMessage: "Trigger succeeded"
    }) }) });
  }
  if (statusCode >= 300) {
    return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { justifyContent: "flex-end", children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { maxWidth: helperPlugin.pxToRem(250), justifyContent: "flex-end", title: message, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { ellipsis: true, textColor: "neutral600", children: message }) }) });
  }
  return null;
};
Message.propTypes = {
  statusCode: PropTypes__default.default.number,
  message: PropTypes__default.default.string
};
Message.defaultProps = {
  statusCode: void 0,
  message: void 0
};
const CancelButton = ({ onCancel }) => {
  const { formatMessage } = reactIntl.useIntl();
  return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { justifyContent: "flex-end", children: /* @__PURE__ */ jsxRuntime.jsx("button", { onClick: onCancel, type: "button", children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, alignItems: "center", children: [
    /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { textColor: "neutral400", children: formatMessage({ id: "Settings.webhooks.trigger.cancel", defaultMessage: "cancel" }) }),
    /* @__PURE__ */ jsxRuntime.jsx(Icon, { as: Icons.Cross, color: "neutral400" })
  ] }) }) });
};
CancelButton.propTypes = { onCancel: PropTypes__default.default.func.isRequired };
const TriggerContainer = ({ isPending, onCancel, response }) => {
  const { statusCode, message } = response;
  const { formatMessage } = reactIntl.useIntl();
  return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { background: "neutral0", padding: 5, shadow: "filterShadow", hasRadius: true, children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Grid, { gap: 4, style: { alignItems: "center" }, children: [
    /* @__PURE__ */ jsxRuntime.jsx(designSystem.GridItem, { col: 3, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { children: formatMessage({
      id: "Settings.webhooks.trigger.test",
      defaultMessage: "Test-trigger"
    }) }) }),
    /* @__PURE__ */ jsxRuntime.jsx(designSystem.GridItem, { col: 3, children: /* @__PURE__ */ jsxRuntime.jsx(Status, { isPending, statusCode }) }),
    /* @__PURE__ */ jsxRuntime.jsx(designSystem.GridItem, { col: 6, children: !isPending ? /* @__PURE__ */ jsxRuntime.jsx(Message, { statusCode, message }) : /* @__PURE__ */ jsxRuntime.jsx(CancelButton, { onCancel }) })
  ] }) });
};
TriggerContainer.defaultProps = {
  isPending: false,
  onCancel() {
  },
  response: {}
};
TriggerContainer.propTypes = {
  isPending: PropTypes__default.default.bool,
  onCancel: PropTypes__default.default.func,
  response: PropTypes__default.default.object
};
const NAME_REGEX = /(^$)|(^[A-Za-z][_0-9A-Za-z ]*$)/;
const URL_REGEX = /(^$)|((https?:\/\/.*)(d*)\/?(.*))/;
const makeWebhookValidationSchema = ({ formatMessage }) => yup__namespace.object().shape({
  name: yup__namespace.string().required(
    formatMessage({
      id: "Settings.webhooks.validation.name.required",
      defaultMessage: "Name is required"
    })
  ).matches(
    NAME_REGEX,
    formatMessage({
      id: "Settings.webhooks.validation.name.regex",
      defaultMessage: "The name must start with a letter and only contain letters, numbers, spaces and underscores"
    })
  ),
  url: yup__namespace.string().required(
    formatMessage({
      id: "Settings.webhooks.validation.url.required",
      defaultMessage: "Url is required"
    })
  ).matches(
    URL_REGEX,
    formatMessage({
      id: "Settings.webhooks.validation.url.regex",
      defaultMessage: "The value must be a valid Url"
    })
  ),
  headers: yup__namespace.lazy((array) => {
    let baseSchema = yup__namespace.array();
    if (array.length === 1) {
      const { key, value } = array[0];
      if (!key && !value) {
        return baseSchema;
      }
    }
    return baseSchema.of(
      yup__namespace.object().shape({
        key: yup__namespace.string().required(
          formatMessage({
            id: "Settings.webhooks.validation.key",
            defaultMessage: "Key is required"
          })
        ),
        value: yup__namespace.string().required(
          formatMessage({
            id: "Settings.webhooks.validation.value",
            defaultMessage: "Value is required"
          })
        )
      })
    );
  }),
  events: yup__namespace.array()
});
const WebhookForm = ({
  handleSubmit,
  triggerWebhook,
  isCreating,
  isTriggering,
  triggerResponse,
  data
}) => {
  const { formatMessage } = reactIntl.useIntl();
  const [showTriggerResponse, setShowTriggerResponse] = React.useState(false);
  const EventTable2 = index.useEnterprise(
    EventTableCE,
    async () => (await Promise.resolve().then(() => require("./index-1e52b373.js"))).EventTableEE
  );
  const mapHeaders = (headers) => {
    if (!Object.keys(headers).length) {
      return [{ key: "", value: "" }];
    }
    return Object.entries(headers).map(([key, value]) => ({ key, value }));
  };
  const formik$1 = formik.useFormik({
    initialValues: {
      name: data?.name || "",
      url: data?.url || "",
      headers: mapHeaders(data?.headers || {}),
      events: data?.events || []
    },
    onSubmit(values, { resetForm, setSubmitting }) {
      handleSubmit(values);
      resetForm({ values });
      setSubmitting(false);
    },
    validationSchema: makeWebhookValidationSchema({ formatMessage }),
    validateOnChange: false,
    validateOnBlur: false
  });
  if (!EventTable2) {
    return null;
  }
  return /* @__PURE__ */ jsxRuntime.jsx(formik.FormikProvider, { value: formik$1, children: /* @__PURE__ */ jsxRuntime.jsxs(helperPlugin.Form, { onSubmit: formik$1.handleSubmit, children: [
    /* @__PURE__ */ jsxRuntime.jsx(
      designSystem.HeaderLayout,
      {
        primaryAction: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, children: [
          /* @__PURE__ */ jsxRuntime.jsx(
            designSystem.Button,
            {
              onClick: () => {
                triggerWebhook();
                setShowTriggerResponse(true);
              },
              variant: "tertiary",
              startIcon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Play, {}),
              disabled: isCreating || isTriggering,
              size: "L",
              children: formatMessage({
                id: "Settings.webhooks.trigger",
                defaultMessage: "Trigger"
              })
            }
          ),
          /* @__PURE__ */ jsxRuntime.jsx(
            designSystem.Button,
            {
              startIcon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Check, {}),
              type: "submit",
              size: "L",
              disabled: !formik$1.dirty,
              loading: formik$1.isSubmitting,
              children: formatMessage({
                id: "global.save",
                defaultMessage: "Save"
              })
            }
          )
        ] }),
        title: isCreating ? formatMessage({
          id: "Settings.webhooks.create",
          defaultMessage: "Create a webhook"
        }) : data?.name,
        navigationAction: /* @__PURE__ */ jsxRuntime.jsx(helperPlugin.Link, { startIcon: /* @__PURE__ */ jsxRuntime.jsx(Icons.ArrowLeft, {}), to: "/settings/webhooks", children: formatMessage({
          id: "global.back",
          defaultMessage: "Back"
        }) })
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(designSystem.ContentLayout, { children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
      showTriggerResponse && /* @__PURE__ */ jsxRuntime.jsx(
        TriggerContainer,
        {
          isPending: isTriggering,
          response: triggerResponse,
          onCancel: () => setShowTriggerResponse(false)
        }
      ),
      /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { background: "neutral0", padding: 8, shadow: "filterShadow", hasRadius: true, children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 6, children: [
        /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Grid, { gap: 6, children: [
          /* @__PURE__ */ jsxRuntime.jsx(designSystem.GridItem, { col: 6, children: /* @__PURE__ */ jsxRuntime.jsx(
            formik.Field,
            {
              as: designSystem.TextInput,
              name: "name",
              error: formik$1?.errors?.name && formik$1.errors.name,
              label: formatMessage({
                id: "global.name",
                defaultMessage: "Name"
              }),
              required: true
            }
          ) }),
          /* @__PURE__ */ jsxRuntime.jsx(designSystem.GridItem, { col: 12, children: /* @__PURE__ */ jsxRuntime.jsx(
            formik.Field,
            {
              as: designSystem.TextInput,
              name: "url",
              error: formik$1?.errors?.url && formik$1.errors.url,
              label: formatMessage({
                id: "Settings.roles.form.input.url",
                defaultMessage: "Url"
              }),
              required: true
            }
          ) })
        ] }),
        /* @__PURE__ */ jsxRuntime.jsx(HeadersInput, {}),
        /* @__PURE__ */ jsxRuntime.jsx(EventTable2, {})
      ] }) })
    ] }) })
  ] }) });
};
WebhookForm.propTypes = {
  data: PropTypes__default.default.object,
  handleSubmit: PropTypes__default.default.func.isRequired,
  triggerWebhook: PropTypes__default.default.func.isRequired,
  isCreating: PropTypes__default.default.bool.isRequired,
  isTriggering: PropTypes__default.default.bool.isRequired,
  triggerResponse: PropTypes__default.default.object
};
WebhookForm.defaultProps = {
  data: void 0,
  triggerResponse: void 0
};
const cleanData = (data) => ({
  ...data,
  headers: data.headers.reduce((acc, { key, value }) => {
    if (key !== "") {
      acc[key] = value;
    }
    return acc;
  }, {})
});
const EditView = () => {
  const {
    params: { id }
  } = reactRouterDom.useRouteMatch("/settings/webhooks/:id");
  const isCreating = id === "create";
  const { replace } = reactRouterDom.useHistory();
  const toggleNotification = helperPlugin.useNotification();
  const { formatAPIError } = helperPlugin.useAPIErrorHandler();
  const queryClient = reactQuery.useQueryClient();
  const { isLoading: isLoadingForModels } = useContentTypes.useContentTypes();
  const { put, get, post } = helperPlugin.useFetchClient();
  const {
    isLoading,
    data: webhookData,
    error: webhookError
  } = reactQuery.useQuery(
    ["webhooks", id],
    async () => {
      const {
        data: { data }
      } = await get(`/admin/webhooks/${id}`);
      return data;
    },
    {
      enabled: !isCreating
    }
  );
  React__namespace.useEffect(() => {
    if (webhookError) {
      toggleNotification({
        type: "warning",
        message: formatAPIError(webhookError)
      });
    }
  }, [webhookError, toggleNotification, formatAPIError]);
  const {
    isLoading: isTriggering,
    data: triggerResponse,
    isIdle: isTriggerIdle,
    mutate
  } = reactQuery.useMutation(() => post(`/admin/webhooks/${id}/trigger`));
  const triggerWebhook = () => mutate(null, {
    onError(error) {
      toggleNotification({
        type: "warning",
        message: formatAPIError(error)
      });
    }
  });
  const createWebhookMutation = reactQuery.useMutation((body) => post("/admin/webhooks", body));
  const updateWebhookMutation = reactQuery.useMutation(({ id: id2, body }) => put(`/admin/webhooks/${id2}`, body));
  const handleSubmit = async (data) => {
    if (isCreating) {
      createWebhookMutation.mutate(cleanData(data), {
        onSuccess({ data: result }) {
          toggleNotification({
            type: "success",
            message: { id: "Settings.webhooks.created" }
          });
          replace(`/settings/webhooks/${result.data.id}`);
        },
        onError(error) {
          toggleNotification({
            type: "warning",
            message: formatAPIError(error)
          });
        }
      });
      return;
    }
    updateWebhookMutation.mutate(
      { id, body: cleanData(data) },
      {
        onSuccess() {
          queryClient.invalidateQueries(["webhooks", id]);
          toggleNotification({
            type: "success",
            message: { id: "notification.form.success.fields" }
          });
        },
        onError(error) {
          toggleNotification({
            type: "warning",
            message: formatAPIError(error)
          });
        }
      }
    );
  };
  if (isLoading || isLoadingForModels) {
    return /* @__PURE__ */ jsxRuntime.jsx(helperPlugin.LoadingIndicatorPage, {});
  }
  return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Main, { children: [
    /* @__PURE__ */ jsxRuntime.jsx(helperPlugin.SettingsPageTitle, { name: "Webhooks" }),
    /* @__PURE__ */ jsxRuntime.jsx(
      WebhookForm,
      {
        ...{
          data: webhookData,
          handleSubmit,
          triggerWebhook,
          isCreating,
          isTriggering,
          isTriggerIdle,
          triggerResponse: triggerResponse?.data.data
        }
      }
    )
  ] });
};
exports.EditView = EditView;
exports.EventTable = EventTable;
//# sourceMappingURL=index-f380be50.js.map
