import { jsx, jsxs } from 'react/jsx-runtime';
import { useState, useMemo } from 'react';
import { css } from '@emotion/css';
import { useTheme2, Field, Select } from '@grafana/ui';
import '@grafana/data';
import { BasicAuth } from './BasicAuth.js';
import { ConfigSubSection } from '../../ConfigSection/ConfigSubSection.js';
import { AuthMethod } from '../types.js';

const defaultOptions = {
  [AuthMethod.BasicAuth]: {
    label: "Basic authentication",
    value: AuthMethod.BasicAuth,
    description: "Authenticate with your data source username and password"
  },
  [AuthMethod.CrossSiteCredentials]: {
    label: "Enable cross-site access control requests",
    value: AuthMethod.CrossSiteCredentials,
    description: "Allow cross-site Access-Control requests with your existing credentials and cookies. This enables the server to authenticate the user and perform authorized requests on their behalf on other domains."
  },
  [AuthMethod.OAuthForward]: {
    label: "Forward OAuth Identity",
    value: AuthMethod.OAuthForward,
    description: "Forward the OAuth access token (and if available: the OIDC ID token) of the user querying to the data source"
  },
  [AuthMethod.NoAuth]: {
    label: "No Authentication",
    value: AuthMethod.NoAuth,
    description: "Data source is available without authentication"
  }
};
const AuthMethodSettings = ({
  selectedMethod,
  mostCommonMethod,
  visibleMethods: visibleMethodsFromProps,
  defaultOptionsOverrides,
  customMethods,
  onAuthMethodSelect,
  basicAuth,
  readOnly
}) => {
  var _a, _b, _c, _d;
  const [authMethodChanged, setAuthMethodChanged] = useState(false);
  const { colors, spacing } = useTheme2();
  const visibleMethods = useMemo(
    () => {
      var _a2;
      return visibleMethodsFromProps != null ? visibleMethodsFromProps : [
        AuthMethod.BasicAuth,
        AuthMethod.OAuthForward,
        AuthMethod.NoAuth,
        ...(_a2 = customMethods == null ? undefined : customMethods.map((m) => m.id)) != null ? _a2 : []
      ];
    },
    [customMethods, visibleMethodsFromProps]
  );
  const hasSelect = visibleMethods.length > 1;
  const preparedOptions = useMemo(() => {
    var _a2;
    const customOptions = (_a2 = customMethods == null ? undefined : customMethods.reduce((acc, method) => {
      acc[method.id] = {
        label: method.label,
        value: method.id,
        description: method.description
      };
      return acc;
    }, {})) != null ? _a2 : {};
    const preparedDefaultOptions = {};
    let k;
    for (k in defaultOptions) {
      preparedDefaultOptions[k] = {
        ...defaultOptions[k],
        ...defaultOptionsOverrides == null ? undefined : defaultOptionsOverrides[k]
      };
    }
    const allOptions = {
      ...customOptions,
      ...preparedDefaultOptions
    };
    return visibleMethods.filter((method) => Boolean(allOptions[method])).map((method) => {
      const option = allOptions[method];
      if (method === mostCommonMethod && hasSelect) {
        return {
          ...option,
          label: `${option.label} (most common)`
        };
      }
      return option;
    });
  }, [visibleMethods, customMethods, defaultOptionsOverrides, mostCommonMethod, hasSelect]);
  let selected = selectedMethod;
  if (!hasSelect) {
    selected = visibleMethods[0];
  } else if (selectedMethod === AuthMethod.NoAuth && mostCommonMethod && !authMethodChanged) {
    selected = mostCommonMethod;
  }
  let AuthFieldsComponent = null;
  if (selected === AuthMethod.BasicAuth && basicAuth) {
    AuthFieldsComponent = /* @__PURE__ */ jsx(BasicAuth, { ...basicAuth, readOnly });
  } else if (selected.startsWith("custom-")) {
    AuthFieldsComponent = (_b = (_a = customMethods == null ? undefined : customMethods.find((m) => m.id === selected)) == null ? undefined : _a.component) != null ? _b : null;
  }
  const title = hasSelect ? "Authentication methods" : (_c = preparedOptions[0].label) != null ? _c : "";
  const description = hasSelect ? "Choose an authentication method to access the data source" : (_d = preparedOptions[0].description) != null ? _d : "";
  const styles = {
    authMethods: css({
      marginTop: spacing(2.5),
      ...hasSelect && {
        padding: spacing(2),
        border: `1px solid ${colors.border.weak}`
      }
    }),
    selectedMethodFields: css({
      marginTop: spacing(1.5)
    })
  };
  return /* @__PURE__ */ jsx(ConfigSubSection, { title, description, children: /* @__PURE__ */ jsxs("div", { className: styles.authMethods, children: [
    hasSelect && /* @__PURE__ */ jsx(Field, { label: "Authentication method", children: /* @__PURE__ */ jsx(
      Select,
      {
        inputId: "auth-method-select",
        options: preparedOptions,
        value: selected,
        onChange: (option) => {
          setAuthMethodChanged(true);
          onAuthMethodSelect(option.value);
        },
        disabled: readOnly
      }
    ) }),
    AuthFieldsComponent && /* @__PURE__ */ jsx("div", { className: styles.selectedMethodFields, children: AuthFieldsComponent })
  ] }) });
};

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