import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
import { useState, useId, useCallback } from 'react';
import { useCopyToClipboard } from 'react-use';
import '@grafana/data';
import { ConfirmModal } from './ConfirmModal.js';
import { DatasetSelector } from './DatasetSelector.js';
import { CatalogSelector } from './CatalogSelector.js';
import { TableSelector } from './TableSelector.js';
import { InlineSwitch, RadioButtonGroup } from '@grafana/ui';
import { EditorMode, QUERY_FORMAT_OPTIONS, QueryFormat } from './types.js';
import { getRawSqlFn } from './utils/sql.utils.js';
import { EditorField } from './EditorField.js';
import { EditorHeader } from './EditorHeader.js';
import { EditorRow } from './EditorRow.js';
import { FlexItem } from './FlexItem.js';
import { InlineSelect } from './InlineSelect.js';
import { Space } from './Space.js';
import { RunQueryButton } from './RunQueryButton.js';

const editorModes = [
  { label: "Builder", value: EditorMode.Builder },
  { label: "Code", value: EditorMode.Code }
];
function QueryHeader({
  db,
  defaultDataset,
  enableDatasets,
  enableCatalogs,
  query,
  queryRowFilter,
  onChange,
  onRunQuery,
  onQueryRowChange,
  isQueryRunnable,
  labels = /* @__PURE__ */ new Map([["dataset", "Dataset"]])
}) {
  const { editorMode } = query;
  const [_, copyToClipboard] = useCopyToClipboard();
  const [showConfirm, setShowConfirm] = useState(false);
  const toRawSql = getRawSqlFn(db);
  const htmlId = useId();
  const catalogsEnabled = enableCatalogs != null ? enableCatalogs : db.disableCatalogs === false;
  const effectiveEnableDatasets = catalogsEnabled ? true : enableDatasets;
  const onEditorModeChange = useCallback(
    (newEditorMode) => {
      if (editorMode === EditorMode.Code) {
        setShowConfirm(true);
        return;
      }
      onChange({ ...query, editorMode: newEditorMode });
    },
    [editorMode, onChange, query]
  );
  const onFormatChange = (e) => {
    const next = { ...query, format: e.value !== undefined ? e.value : QueryFormat.Table };
    onChange(next);
  };
  const onDatasetChange = (e) => {
    const datasetValue = e.value || undefined;
    if (datasetValue === query.dataset) {
      return;
    }
    const next = {
      ...query,
      dataset: datasetValue,
      table: undefined,
      sql: undefined,
      rawSql: ""
    };
    onChange(next);
  };
  const onCatalogChange = (catalog) => {
    const catalogValue = catalog || undefined;
    if (catalogValue === query.catalog) {
      return;
    }
    const next = {
      ...query,
      catalog: catalogValue,
      dataset: undefined,
      // Reset dataset (which acts as schema when catalog is present)
      table: undefined,
      sql: undefined,
      rawSql: ""
    };
    onChange(next);
  };
  const onTableChange = (e) => {
    if (e.value === query.table) {
      return;
    }
    const next = {
      ...query,
      table: e.value,
      sql: undefined,
      rawSql: ""
    };
    onChange(next);
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsxs(EditorHeader, { children: [
      /* @__PURE__ */ jsx(
        InlineSelect,
        {
          label: "Format",
          value: query.format,
          placeholder: "Select format",
          menuShouldPortal: true,
          onChange: onFormatChange,
          options: QUERY_FORMAT_OPTIONS
        }
      ),
      editorMode === EditorMode.Builder && /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(
          InlineSwitch,
          {
            id: `sql-filter-${htmlId}`,
            label: "Filter",
            transparent: true,
            showLabel: true,
            value: queryRowFilter.filter,
            onChange: (ev) => ev.target instanceof HTMLInputElement && onQueryRowChange({ ...queryRowFilter, filter: ev.target.checked })
          }
        ),
        /* @__PURE__ */ jsx(
          InlineSwitch,
          {
            id: `sql-group-${htmlId}`,
            label: "Group",
            transparent: true,
            showLabel: true,
            value: queryRowFilter.group,
            onChange: (ev) => ev.target instanceof HTMLInputElement && onQueryRowChange({ ...queryRowFilter, group: ev.target.checked })
          }
        ),
        /* @__PURE__ */ jsx(
          InlineSwitch,
          {
            id: `sql-order-${htmlId}`,
            label: "Order",
            transparent: true,
            showLabel: true,
            value: queryRowFilter.order,
            onChange: (ev) => ev.target instanceof HTMLInputElement && onQueryRowChange({ ...queryRowFilter, order: ev.target.checked })
          }
        ),
        /* @__PURE__ */ jsx(
          InlineSwitch,
          {
            id: `sql-preview-${htmlId}`,
            label: "Preview",
            transparent: true,
            showLabel: true,
            value: queryRowFilter.preview,
            onChange: (ev) => ev.target instanceof HTMLInputElement && onQueryRowChange({ ...queryRowFilter, preview: ev.target.checked })
          }
        )
      ] }),
      /* @__PURE__ */ jsx(FlexItem, { grow: 1 }),
      /* @__PURE__ */ jsx(RunQueryButton, { queryInvalid: !isQueryRunnable, onClick: () => onRunQuery() }),
      /* @__PURE__ */ jsx(RadioButtonGroup, { options: editorModes, size: "sm", value: editorMode, onChange: onEditorModeChange }),
      /* @__PURE__ */ jsx(
        ConfirmModal,
        {
          isOpen: showConfirm,
          onCopy: () => {
            setShowConfirm(false);
            copyToClipboard(query.rawSql);
            onChange({
              ...query,
              rawSql: toRawSql(query),
              editorMode: EditorMode.Builder
            });
          },
          onDiscard: () => {
            setShowConfirm(false);
            onChange({
              ...query,
              rawSql: toRawSql(query),
              editorMode: EditorMode.Builder
            });
          },
          onCancel: () => setShowConfirm(false)
        }
      )
    ] }),
    editorMode === EditorMode.Builder && /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx(Space, { v: 0.5 }),
      /* @__PURE__ */ jsxs(EditorRow, { children: [
        catalogsEnabled && /* @__PURE__ */ jsx(EditorField, { label: labels.get("catalog") || "Catalog", width: 25, children: /* @__PURE__ */ jsx(
          CatalogSelector,
          {
            db,
            inputId: `sql-catalog-${htmlId}`,
            value: query.catalog === undefined ? null : query.catalog,
            onChange: onCatalogChange
          }
        ) }),
        effectiveEnableDatasets && /* @__PURE__ */ jsx(
          EditorField,
          {
            label: catalogsEnabled ? labels.get("schema") || "Schema" : labels.get("dataset") || "Dataset",
            width: 25,
            children: /* @__PURE__ */ jsx(
              DatasetSelector,
              {
                db,
                inputId: catalogsEnabled ? `sql-schema-${htmlId}` : `sql-dataset-${htmlId}`,
                "data-testid": catalogsEnabled ? "schema-selector" : "dataset-selector",
                dataset: catalogsEnabled ? undefined : defaultDataset,
                value: query.dataset === undefined ? null : query.dataset,
                onChange: onDatasetChange,
                catalog: catalogsEnabled ? query.catalog : undefined
              }
            )
          }
        ),
        /* @__PURE__ */ jsx(EditorField, { label: labels.get("table") || "Table", width: 25, children: /* @__PURE__ */ jsx(
          TableSelector,
          {
            db,
            inputId: `sql-table-${htmlId}`,
            dataset: query.dataset || (catalogsEnabled ? undefined : defaultDataset),
            catalog: catalogsEnabled ? query.catalog : undefined,
            query,
            value: query.table === undefined ? null : query.table,
            onChange: onTableChange,
            enableCatalogs: catalogsEnabled,
            applyDefault: true
          }
        ) })
      ] })
    ] })
  ] });
}

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