import { jsxs, jsx } from 'react/jsx-runtime';
import { css } from '@emotion/css';
import { uniqueId } from 'lodash';
import { PureComponent } from 'react';
import '@grafana/data';
import { useStyles2 } from '../../themes/ThemeContext.js';
import 'micro-memoize';
import '@emotion/react';
import 'tinycolor2';
import '../../utils/skeleton.js';
import { Button } from '../Button/Button.js';
import '../Button/ButtonGroup.js';
import { FormField } from '../FormField/FormField.js';
import { Icon } from '../Icon/Icon.js';
import { SecretFormField } from '../SecretFormField/SecretFormField.js';

const getCustomHeaderRowStyles = () => ({
  layout: css({
    display: "flex",
    alignItems: "center",
    marginBottom: "4px",
    "> *": {
      marginLeft: "4px",
      marginBottom: 0,
      height: "100%",
      "&:first-child, &:last-child": {
        marginLeft: 0
      }
    }
  })
});
const CustomHeaderRow = ({ header, onBlur, onChange, onRemove, onReset }) => {
  const styles = useStyles2(getCustomHeaderRowStyles);
  return /* @__PURE__ */ jsxs("div", { className: styles.layout, children: [
    /* @__PURE__ */ jsx(
      FormField,
      {
        label: "Header",
        name: "name",
        placeholder: "X-Custom-Header",
        labelWidth: 5,
        value: header.name || "",
        onChange: (e) => onChange({ ...header, name: e.target.value }),
        onBlur
      }
    ),
    /* @__PURE__ */ jsx(
      SecretFormField,
      {
        label: "Value",
        "aria-label": "Value",
        name: "value",
        isConfigured: header.configured,
        value: header.value,
        labelWidth: 5,
        inputWidth: header.configured ? 11 : 12,
        placeholder: "Header Value",
        onReset: () => onReset(header.id),
        onChange: (e) => onChange({ ...header, value: e.target.value }),
        onBlur
      }
    ),
    /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        "aria-label": "Remove header",
        variant: "secondary",
        size: "xs",
        onClick: (_e) => onRemove(header.id),
        children: /* @__PURE__ */ jsx(Icon, { name: "trash-alt" })
      }
    )
  ] });
};
CustomHeaderRow.displayName = "CustomHeaderRow";
class CustomHeadersSettings extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      headers: []
    };
    this.updateSettings = () => {
      const { headers } = this.state;
      const newJsonData = Object.fromEntries(
        Object.entries(this.props.dataSourceConfig.jsonData).filter(([key, val]) => !key.startsWith("httpHeaderName"))
      );
      const newSecureJsonData = Object.fromEntries(
        Object.entries(this.props.dataSourceConfig.secureJsonData || {}).filter(
          ([key, val]) => !key.startsWith("httpHeaderValue")
        )
      );
      for (const [index, header] of headers.entries()) {
        newJsonData[`httpHeaderName${index + 1}`] = header.name;
        if (!header.configured) {
          newSecureJsonData[`httpHeaderValue${index + 1}`] = header.value;
        }
      }
      this.props.onChange({
        ...this.props.dataSourceConfig,
        jsonData: newJsonData,
        secureJsonData: newSecureJsonData
      });
    };
    this.onHeaderAdd = () => {
      this.setState((prevState) => {
        return { headers: [...prevState.headers, { id: uniqueId(), name: "", value: "", configured: false }] };
      });
    };
    this.onHeaderChange = (headerIndex, value) => {
      this.setState(({ headers }) => {
        return {
          headers: headers.map((item, index) => {
            if (headerIndex !== index) {
              return item;
            }
            return { ...value };
          })
        };
      });
    };
    this.onHeaderReset = (headerId) => {
      this.setState(({ headers }) => {
        return {
          headers: headers.map((h, i) => {
            if (h.id !== headerId) {
              return h;
            }
            return {
              ...h,
              value: "",
              configured: false
            };
          })
        };
      });
    };
    this.onHeaderRemove = (headerId) => {
      this.setState(
        ({ headers }) => ({
          headers: headers.filter((h) => h.id !== headerId)
        }),
        this.updateSettings
      );
    };
    const { jsonData, secureJsonData, secureJsonFields } = this.props.dataSourceConfig;
    this.state = {
      headers: Object.keys(jsonData).sort().filter((key) => key.startsWith("httpHeaderName")).map((key, index) => {
        return {
          id: uniqueId(),
          name: jsonData[key],
          value: secureJsonData !== void 0 ? secureJsonData[key] : "",
          configured: secureJsonFields && secureJsonFields[`httpHeaderValue${index + 1}`] || false
        };
      })
    };
  }
  render() {
    const { headers } = this.state;
    const { dataSourceConfig } = this.props;
    return /* @__PURE__ */ jsxs("div", { className: "gf-form-group", children: [
      /* @__PURE__ */ jsx("div", { className: "gf-form", children: /* @__PURE__ */ jsx("h6", { children: "Custom HTTP Headers" }) }),
      /* @__PURE__ */ jsx("div", { children: headers.map((header, i) => /* @__PURE__ */ jsx(
        CustomHeaderRow,
        {
          header,
          onChange: (h) => {
            this.onHeaderChange(i, h);
          },
          onBlur: this.updateSettings,
          onRemove: this.onHeaderRemove,
          onReset: this.onHeaderReset
        },
        header.id
      )) }),
      !dataSourceConfig.readOnly && /* @__PURE__ */ jsx("div", { className: "gf-form", children: /* @__PURE__ */ jsx(
        Button,
        {
          variant: "secondary",
          icon: "plus",
          type: "button",
          onClick: (e) => {
            this.onHeaderAdd();
          },
          children: "Add header"
        }
      ) })
    ] });
  }
}

export { CustomHeadersSettings, CustomHeadersSettings as default };
//# sourceMappingURL=CustomHeadersSettings.js.map
