import { jsx } from 'react/jsx-runtime';
import { useEffect } from 'react';
import { useAsync } from 'react-use';
import '@grafana/data';
import { Select } from '@grafana/ui';
import { toOption } from './types.js';

const DatasetSelector = ({
  db,
  dataset,
  catalog,
  value,
  onChange,
  disabled,
  className,
  applyDefault,
  inputId,
  enableCatalogs,
  "data-testid": dataTestId
}) => {
  const state = useAsync(async () => {
    if (dataset) {
      onChange(toOption(dataset));
      return [toOption(dataset)];
    }
    const datasets = await db.datasets(catalog);
    return datasets.map(toOption);
  }, [catalog]);
  useEffect(() => {
    if (!applyDefault) {
      return;
    }
    if (!value) {
      if (state.value && state.value[0]) {
        onChange(state.value[0]);
      }
    } else {
      if (state.value && state.value.find((v) => v.value === value) === undefined) {
        if (state.value.length > 0) {
          onChange(state.value[0]);
        }
      }
    }
  }, [state.value, value, applyDefault, onChange]);
  return /* @__PURE__ */ jsx(
    Select,
    {
      inputId,
      className,
      "aria-label": "Dataset selector",
      value,
      options: state.value,
      onChange,
      disabled,
      isLoading: state.loading,
      menuShouldPortal: true,
      "data-testid": dataTestId,
      placeholder: enableCatalogs ? "Select schema" : "Select dataset"
    }
  );
};

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