import { jsxs, jsx } from "react/jsx-runtime";
import { Layout, Main, HeaderLayout, Button, ContentLayout, Flex, Typography, Grid, GridItem, ToggleInput, Select, Option, MultiSelect, MultiSelectOption } from "@strapi/design-system";
import { useNotification, useOverlayBlocker, useFetchClient, getYupInnerErrors, translatedErrors, useFocusWhenNavigate, useRBAC, SettingsPageTitle, LoadingIndicatorPage, CheckPagePermissions } from "@strapi/helper-plugin";
import { Check } from "@strapi/icons";
import isEqual from "lodash/isEqual";
import { useIntl } from "react-intl";
import { useSelector } from "react-redux";
import { u as useAdminRoles } from "./useAdminRoles-7ab5d521.mjs";
import { s as selectAdminPermissions } from "./AuthenticatedApp-4e25ce97.mjs";
import * as React from "react";
import produce from "immer";
import omit from "lodash/omit";
import pick from "lodash/pick";
import set from "lodash/set";
import * as yup from "yup";
import { ValidationError } from "yup";
import { f as formatAPIErrors } from "./formatAPIErrors-db6ed675.mjs";
import "react-query";
import "semver/functions/lt";
import "semver/functions/valid";
import "./index-466b22f5.mjs";
import "react-dom/client";
import "invariant";
import "lodash/isFunction";
import "lodash/merge";
import "react-helmet";
import "react-router-dom";
import "@radix-ui/react-context";
import "@strapi/design-system/v2";
import "formik";
import "lodash/camelCase";
import "styled-components";
import "lodash/defaultsDeep";
import "qs";
import "lodash/get";
import "@reduxjs/toolkit";
import "react-dnd";
import "react-dnd-html5-backend";
import "lodash/cloneDeep";
const initialState = {
  fieldsToPick: [],
  formErrors: {},
  initialData: {},
  isLoading: true,
  modifiedData: {},
  showHeaderButtonLoader: false,
  showHeaderLoader: true
};
const reducer = (state, action) => produce(state, (draftState) => {
  switch (action.type) {
    case "GET_DATA_SUCCEEDED": {
      draftState.isLoading = false;
      draftState.showHeaderLoader = false;
      draftState.initialData = pick(action.data, state.fieldsToPick);
      draftState.modifiedData = pick(action.data, state.fieldsToPick);
      break;
    }
    case "ON_CANCEL": {
      draftState.modifiedData = state.initialData;
      draftState.formErrors = {};
      break;
    }
    case "ON_CHANGE": {
      if (action.keys.includes("username") && !action.value) {
        set(draftState.modifiedData, action.keys.split("."), null);
      } else {
        set(draftState.modifiedData, action.keys.split("."), action.value);
      }
      break;
    }
    case "ON_SUBMIT": {
      draftState.showHeaderButtonLoader = true;
      break;
    }
    case "ON_SUBMIT_SUCCEEDED": {
      draftState.initialData = pick(action.data, state.fieldsToPick);
      draftState.modifiedData = pick(action.data, state.fieldsToPick);
      draftState.showHeaderButtonLoader = false;
      break;
    }
    case "SET_ERRORS": {
      draftState.formErrors = action.errors;
      draftState.showHeaderButtonLoader = false;
      break;
    }
    default:
      return draftState;
  }
});
const checkFormValidity = async (data, schema2) => {
  let errors = null;
  try {
    await schema2.validate(data, { abortEarly: false });
  } catch (err) {
    if (err instanceof ValidationError) {
      errors = getYupInnerErrors(err);
    }
  }
  return errors;
};
const useSettingsForm = (schema2, cbSuccess, fieldsToPick) => {
  const [
    { formErrors, initialData, isLoading, modifiedData, showHeaderButtonLoader, showHeaderLoader },
    dispatch
  ] = React.useReducer(reducer, { ...initialState, fieldsToPick });
  const toggleNotification = useNotification();
  const { lockApp, unlockApp } = useOverlayBlocker();
  const { get, put } = useFetchClient();
  React.useEffect(() => {
    const getData = async () => {
      try {
        const {
          data: { data }
        } = await get("/admin/providers/options");
        dispatch({
          type: "GET_DATA_SUCCEEDED",
          data,
          fieldsToPick
        });
      } catch (err) {
        toggleNotification({
          type: "warning",
          message: { id: "notification.error" }
        });
      }
    };
    getData();
  }, []);
  const handleCancel = () => {
    dispatch({
      type: "ON_CANCEL"
    });
  };
  const handleChange = ({
    target: { name, value }
  }) => {
    dispatch({
      type: "ON_CHANGE",
      keys: name,
      value
    });
  };
  const setField = (fieldName, value) => {
    dispatch({
      type: "ON_CHANGE",
      keys: fieldName,
      value
    });
  };
  const handleSubmit = async (e) => {
    e.preventDefault();
    const errors = await checkFormValidity(modifiedData, schema2);
    dispatch({
      type: "SET_ERRORS",
      errors: errors || {}
    });
    if (!errors) {
      try {
        lockApp();
        dispatch({
          type: "ON_SUBMIT"
        });
        const cleanedData = omit(modifiedData, ["confirmPassword", "registrationToken"]);
        if (cleanedData.roles) {
          cleanedData.roles = cleanedData.roles.map((role) => role.id);
        }
        if (cleanedData.ssoLockedRoles) {
          cleanedData.ssoLockedRoles = [...new Set(cleanedData.ssoLockedRoles)];
        }
        const {
          data: { data }
        } = await put("/admin/providers/options", cleanedData);
        cbSuccess(data);
        dispatch({
          type: "ON_SUBMIT_SUCCEEDED",
          data
        });
        toggleNotification({
          type: "success",
          message: { id: "notification.success.saved" }
        });
      } catch (err) {
        const data = err?.response?.payload ?? { data: {} };
        if (!!data?.data && typeof data.data === "string") {
          toggleNotification({
            type: "warning",
            message: data.data
          });
        } else {
          toggleNotification({
            type: "warning",
            message: data.message
          });
        }
        const apiErrors = formatAPIErrors(data);
        dispatch({
          type: "SET_ERRORS",
          errors: apiErrors
        });
      } finally {
        unlockApp();
      }
    }
  };
  return [
    { formErrors, initialData, isLoading, modifiedData, showHeaderButtonLoader, showHeaderLoader },
    dispatch,
    { handleCancel, handleChange, handleSubmit, setField }
  ];
};
const schema = yup.object().shape({
  autoRegister: yup.bool().required(translatedErrors.required),
  defaultRole: yup.mixed().when("autoRegister", (value, initSchema) => {
    return value ? initSchema.required(translatedErrors.required) : initSchema.nullable();
  }),
  ssoLockedRoles: yup.array().nullable().of(
    yup.mixed().when("ssoLockedRoles", (value, initSchema) => {
      return value ? initSchema.required(translatedErrors.required) : initSchema.nullable();
    })
  )
});
const SingleSignOn = () => {
  useFocusWhenNavigate();
  const { formatMessage } = useIntl();
  const permissions = useSelector(selectAdminPermissions);
  const {
    isLoading: isLoadingPermissions,
    allowedActions: { canUpdate, canReadRoles }
  } = useRBAC({
    ...permissions.settings.sso,
    readRoles: permissions.settings.roles.read
  });
  const [
    { formErrors, initialData, isLoading: isLoadingForm, modifiedData, showHeaderButtonLoader },
    ,
    { handleChange, handleSubmit }
  ] = useSettingsForm(schema, () => {
  }, ["autoRegister", "defaultRole", "ssoLockedRoles"]);
  const { roles, isLoading: isLoadingRoles } = useAdminRoles(void 0, {
    enabled: canReadRoles
  });
  const isLoading = isLoadingPermissions || isLoadingRoles || isLoadingForm;
  return /* @__PURE__ */ jsxs(Layout, { children: [
    /* @__PURE__ */ jsx(SettingsPageTitle, { name: "SSO" }),
    /* @__PURE__ */ jsx(Main, { tabIndex: -1, children: /* @__PURE__ */ jsxs("form", { onSubmit: handleSubmit, children: [
      /* @__PURE__ */ jsx(
        HeaderLayout,
        {
          primaryAction: /* @__PURE__ */ jsx(
            Button,
            {
              "data-testid": "save-button",
              disabled: isEqual(initialData, modifiedData),
              loading: showHeaderButtonLoader,
              startIcon: /* @__PURE__ */ jsx(Check, {}),
              type: "submit",
              size: "L",
              children: formatMessage({
                id: "global.save",
                defaultMessage: "Save"
              })
            }
          ),
          title: formatMessage({ id: "Settings.sso.title", defaultMessage: "Single Sign-On" }),
          subtitle: formatMessage({
            id: "Settings.sso.description",
            defaultMessage: "Configure the settings for the Single Sign-On feature."
          })
        }
      ),
      /* @__PURE__ */ jsx(ContentLayout, { children: isLoading ? /* @__PURE__ */ jsx(LoadingIndicatorPage, {}) : /* @__PURE__ */ jsxs(
        Flex,
        {
          direction: "column",
          alignItems: "stretch",
          gap: 4,
          background: "neutral0",
          padding: 6,
          shadow: "filterShadow",
          hasRadius: true,
          children: [
            /* @__PURE__ */ jsx(Typography, { variant: "delta", as: "h2", children: formatMessage({
              id: "global.settings",
              defaultMessage: "Settings"
            }) }),
            /* @__PURE__ */ jsxs(Grid, { gap: 4, children: [
              /* @__PURE__ */ jsx(GridItem, { col: 6, m: 6, s: 12, children: /* @__PURE__ */ jsx(
                ToggleInput,
                {
                  "aria-label": "autoRegister",
                  "data-testid": "autoRegister",
                  disabled: !canUpdate,
                  checked: modifiedData.autoRegister,
                  hint: formatMessage({
                    id: "Settings.sso.form.registration.description",
                    defaultMessage: "Create new user on SSO login if no account exists"
                  }),
                  label: formatMessage({
                    id: "Settings.sso.form.registration.label",
                    defaultMessage: "Auto-registration"
                  }),
                  name: "autoRegister",
                  offLabel: formatMessage({
                    id: "app.components.ToggleCheckbox.off-label",
                    defaultMessage: "Off"
                  }),
                  onLabel: formatMessage({
                    id: "app.components.ToggleCheckbox.on-label",
                    defaultMessage: "On"
                  }),
                  onChange: (e) => {
                    handleChange({
                      target: { name: "autoRegister", value: e.target.checked }
                    });
                  }
                }
              ) }),
              /* @__PURE__ */ jsx(GridItem, { col: 6, m: 6, s: 12, children: /* @__PURE__ */ jsx(
                Select,
                {
                  disabled: !canUpdate,
                  hint: formatMessage({
                    id: "Settings.sso.form.defaultRole.description",
                    defaultMessage: "It will attach the new authenticated user to the selected role"
                  }),
                  error: formErrors.defaultRole ? formatMessage({
                    id: formErrors.defaultRole.id,
                    defaultMessage: formErrors.defaultRole.id
                  }) : "",
                  label: formatMessage({
                    id: "Settings.sso.form.defaultRole.label",
                    defaultMessage: "Default role"
                  }),
                  name: "defaultRole",
                  onChange: (value) => {
                    handleChange({ target: { name: "defaultRole", value } });
                  },
                  placeholder: formatMessage({
                    id: "components.InputSelect.option.placeholder",
                    defaultMessage: "Choose here"
                  }),
                  value: modifiedData.defaultRole,
                  children: roles.map(({ id, name }) => /* @__PURE__ */ jsx(Option, { value: id.toString(), children: name }, id))
                }
              ) }),
              /* @__PURE__ */ jsx(GridItem, { col: 6, m: 6, s: 12, children: /* @__PURE__ */ jsx(
                MultiSelect,
                {
                  disabled: !canUpdate,
                  hint: formatMessage({
                    id: "Settings.sso.form.localAuthenticationLock.description",
                    defaultMessage: "Select the roles for which you want to disable the local authentication"
                  }),
                  error: formErrors.ssoLockedRoles ? formatMessage({
                    id: formErrors.ssoLockedRoles.id,
                    defaultMessage: formErrors.ssoLockedRoles.id
                  }) : "",
                  label: formatMessage({
                    id: "Settings.sso.form.localAuthenticationLock.label",
                    defaultMessage: "Local authentication lock-out"
                  }),
                  name: "ssoLockedRoles",
                  onChange: (value) => {
                    handleChange({ target: { name: "ssoLockedRoles", value } });
                  },
                  placeholder: formatMessage({
                    id: "components.InputSelect.option.placeholder",
                    defaultMessage: "Choose here"
                  }),
                  onClear: () => {
                    handleChange({ target: { name: "ssoLockedRoles" } });
                  },
                  value: modifiedData.ssoLockedRoles || [],
                  withTags: true,
                  children: roles.map(({ id, name }) => /* @__PURE__ */ jsx(MultiSelectOption, { value: id.toString(), children: name }, id))
                }
              ) })
            ] })
          ]
        }
      ) })
    ] }) })
  ] });
};
const ProtectedSSO = () => {
  const permissions = useSelector(selectAdminPermissions);
  return /* @__PURE__ */ jsx(CheckPagePermissions, { permissions: permissions.settings.sso.main, children: /* @__PURE__ */ jsx(SingleSignOn, {}) });
};
export {
  SingleSignOn,
  ProtectedSSO as default
};
//# sourceMappingURL=index-a983e7fe.mjs.map
