import { jsxs, jsx } from 'react/jsx-runtime';
import { useRef, useState, useEffect } from 'react';
import '@hello-pangea/dnd';
import { useTheme2, Tooltip, Icon, Button } from '@grafana/ui';
import { cx, css } from '@emotion/css';
import '@grafana/data';
import { OperationHeader } from './OperationHeader.js';
import { getOperationParamEditor, getOperationParamId } from './OperationParamEditor.js';
import { v4 } from 'uuid';
import '../../QueryEditor/types.js';
import 'lodash';
import '../../QueryEditor/EditorList.js';
import { EditorStack } from '../../QueryEditor/EditorStack.js';
import '../../QueryEditor/Space.js';
import 'react-use';
import '../../QueryEditor/QueryHeader.js';
import 'react-virtualized-auto-sizer';
import 'sql-formatter-plus';
import '../../SQLEditor/standardSql/language.js';
import '@grafana/runtime';
import '../../SQLEditor/utils/debugger.js';
import '../../SQLEditor/standardSql/macros.js';
import '../../QueryEditor/visual-query-builder/AwesomeQueryBuilder.js';
import '../../QueryEditor/visual-query-builder/WhereRow.js';
import '../../QueryEditor/visual-query-builder/EditorField.js';
import 'rxjs';
import 'rxjs/operators';

function OperationEditorBody({
  provided,
  flash,
  isConflicting,
  highlight,
  index,
  queryModeller,
  onChange,
  onRemove,
  onToggle,
  operation,
  definition,
  query,
  timeRange,
  onRunQuery,
  datasource
}) {
  const theme = useTheme2();
  const styles = getStyles(theme, isConflicting);
  const shouldFlash = useFlash(flash);
  const { current: id } = useRef(v4());
  const onParamValueChanged = (paramIdx, value) => {
    const update = { ...operation, params: [...operation.params] };
    update.params[paramIdx] = value;
    callParamChangedThenOnChange(definition, update, index, paramIdx, onChange);
  };
  const onAddRestParam = () => {
    const update = { ...operation, params: [...operation.params, ""] };
    callParamChangedThenOnChange(definition, update, index, operation.params.length, onChange);
  };
  const onRemoveRestParam = (paramIdx) => {
    const update = {
      ...operation,
      params: [...operation.params.slice(0, paramIdx), ...operation.params.slice(paramIdx + 1)]
    };
    callParamChangedThenOnChange(definition, update, index, paramIdx, onChange);
  };
  let restParam;
  if (definition.params.length > 0) {
    const lastParamDef = definition.params[definition.params.length - 1];
    if (lastParamDef.restParam) {
      restParam = renderAddRestParamButton(lastParamDef, onAddRestParam, index, operation.params.length, styles);
    }
  }
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: cx(styles.card, {
        [styles.cardHighlight]: shouldFlash || highlight,
        [styles.cardError]: isConflicting,
        [styles.disabled]: operation.disabled
      }),
      ref: provided.innerRef,
      ...provided.draggableProps,
      "data-testid": `operations.${index}.wrapper`,
      children: [
        /* @__PURE__ */ jsx(
          OperationHeader,
          {
            operation,
            dragHandleProps: provided.dragHandleProps,
            definition,
            index,
            onChange,
            onRemove,
            onToggle,
            queryModeller
          }
        ),
        /* @__PURE__ */ jsx("div", { className: styles.body, children: operation.params.map((param, paramIndex) => {
          const paramDef = definition.params[Math.min(definition.params.length - 1, paramIndex)];
          const Editor = getOperationParamEditor(paramDef);
          return /* @__PURE__ */ jsxs("div", { className: styles.paramRow, children: [
            !paramDef.hideName && /* @__PURE__ */ jsxs("div", { className: styles.paramName, children: [
              /* @__PURE__ */ jsx("label", { htmlFor: getOperationParamId(id, paramIndex), children: paramDef.name }),
              paramDef.description && /* @__PURE__ */ jsx(Tooltip, { placement: "top", content: paramDef.description, theme: "info", children: /* @__PURE__ */ jsx(Icon, { name: "info-circle", size: "sm", className: styles.infoIcon }) })
            ] }),
            /* @__PURE__ */ jsx("div", { className: styles.paramValue, children: /* @__PURE__ */ jsxs(EditorStack, { gap: 0.5, direction: "row", alignItems: "center", wrap: false, children: [
              /* @__PURE__ */ jsx(
                Editor,
                {
                  index: paramIndex,
                  paramDef,
                  value: operation.params[paramIndex],
                  operation,
                  operationId: id,
                  onChange: onParamValueChanged,
                  onRunQuery,
                  query,
                  datasource,
                  timeRange,
                  queryModeller
                }
              ),
              paramDef.restParam && (operation.params.length > definition.params.length || paramDef.optional) && /* @__PURE__ */ jsx(
                Button,
                {
                  "data-testid": `operations.${index}.remove-rest-param`,
                  size: "sm",
                  fill: "text",
                  icon: "times",
                  variant: "secondary",
                  title: `Remove ${paramDef.name}`,
                  onClick: () => onRemoveRestParam(paramIndex)
                }
              )
            ] }) })
          ] }, `${paramIndex}-1`);
        }) }),
        restParam,
        index < query.operations.length - 1 && /* @__PURE__ */ jsxs("div", { className: styles.arrow, children: [
          /* @__PURE__ */ jsx("div", { className: styles.arrowLine }),
          /* @__PURE__ */ jsx("div", { className: styles.arrowArrow })
        ] })
      ]
    }
  );
}
const getStyles = (theme, isConflicting) => {
  return {
    cardWrapper: css({
      alignItems: "stretch"
    }),
    error: css({
      marginBottom: theme.spacing(1)
    }),
    card: css({
      background: theme.colors.background.primary,
      border: `1px solid ${theme.colors.border.medium}`,
      cursor: "grab",
      borderRadius: theme.shape.radius.default,
      position: "relative",
      transition: "all 0.5s ease-in 0s",
      height: isConflicting ? "auto" : "100%"
    }),
    disabled: css({
      opacity: 0.5,
      transition: "none"
    }),
    cardError: css({
      boxShadow: `0px 0px 4px 0px ${theme.colors.warning.main}`,
      border: `1px solid ${theme.colors.warning.main}`
    }),
    cardHighlight: css({
      boxShadow: `0px 0px 4px 0px ${theme.colors.primary.border}`,
      border: `1px solid ${theme.colors.primary.border}`
    }),
    infoIcon: css({
      marginLeft: theme.spacing(0.5),
      color: theme.colors.text.secondary,
      ":hover": {
        color: theme.colors.text.primary
      }
    }),
    body: css({
      margin: theme.spacing(1, 1, 0.5, 1),
      display: "table"
    }),
    paramRow: css({
      label: "paramRow",
      display: "table-row",
      verticalAlign: "middle"
    }),
    paramName: css({
      display: "table-cell",
      padding: theme.spacing(0, 1, 0, 0),
      fontSize: theme.typography.bodySmall.fontSize,
      fontWeight: theme.typography.fontWeightMedium,
      verticalAlign: "middle",
      height: "32px"
    }),
    paramValue: css({
      label: "paramValue",
      display: "table-cell",
      verticalAlign: "middle"
    }),
    restParam: css({
      padding: theme.spacing(0, 1, 1, 1)
    }),
    arrow: css({
      position: "absolute",
      top: "0",
      right: "-18px",
      display: "flex"
    }),
    arrowLine: css({
      height: "2px",
      width: "8px",
      backgroundColor: theme.colors.border.strong,
      position: "relative",
      top: "14px"
    }),
    arrowArrow: css({
      width: 0,
      height: 0,
      borderTop: `5px solid transparent`,
      borderBottom: `5px solid transparent`,
      borderLeft: `7px solid ${theme.colors.border.strong}`,
      position: "relative",
      top: "10px"
    })
  };
};
function useFlash(flash) {
  const [keepFlash, setKeepFlash] = useState(true);
  useEffect(() => {
    let t;
    if (flash) {
      t = setTimeout(() => {
        setKeepFlash(false);
      }, 1e3);
    } else {
      setKeepFlash(true);
    }
    return () => clearTimeout(t);
  }, [flash]);
  return keepFlash && flash;
}
function callParamChangedThenOnChange(def, operation, operationIndex, paramIndex, onChange) {
  if (def.paramChangedHandler) {
    onChange(operationIndex, def.paramChangedHandler(paramIndex, operation, def));
  } else {
    onChange(operationIndex, operation);
  }
}
function renderAddRestParamButton(paramDef, onAddRestParam, operationIndex, paramIndex, styles) {
  return /* @__PURE__ */ jsx("div", { className: styles.restParam, children: /* @__PURE__ */ jsx(
    Button,
    {
      size: "sm",
      icon: "plus",
      title: `Add ${paramDef.name}`.trimEnd(),
      variant: "secondary",
      onClick: onAddRestParam,
      "data-testid": `operations.${operationIndex}.add-rest-param`,
      children: paramDef.name
    }
  ) }, `${paramIndex}-2`);
}

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