import { Select } from '@grafana/ui';
import { isEqual } from 'lodash';
import React, { useRef, useState, useMemo, useEffect } from 'react';
import { defaultKey } from './types.js';

function ResourceSelector(props) {
  const propsDependencies = props.dependencies;
  const propsOnChange = props.onChange;
  const dependencies = useRef(props.dependencies);
  const fetched = useRef(false);
  const resource = useRef(props.value || props.default || null);
  const [resources, setResources] = useState(
    resource.current ? [resource.current] : []
  );
  const [isLoading, setIsLoading] = useState(false);
  const defaultOpts = useMemo(() => {
    const opts = [
      {
        label: `default (${props.default})`,
        value: defaultKey,
        description: `Default value set in the data source`
      }
    ];
    if (props.value && props.value !== defaultKey) {
      opts.push({ label: props.value, value: props.value });
    }
    return opts;
  }, [props.default, props.value]);
  const [options, setOptions] = useState(props.default ? defaultOpts : []);
  useEffect(() => {
    if (props.resources !== void 0) {
      setResources(props.resources);
    }
  }, [props.resources]);
  useEffect(() => {
    const newOptions = props.default ? defaultOpts : [];
    if (resources.length) {
      resources.forEach((r) => {
        const value = typeof r === "string" ? r : r.value;
        if (!newOptions.find((o) => o.value === value)) {
          typeof r === "string" ? newOptions.push({ label: r, value: r }) : newOptions.push(r);
        }
      });
      setOptions(newOptions);
    } else {
      setOptions([]);
    }
  }, [resources, defaultOpts, props.default]);
  useEffect(() => {
    if (!isEqual(propsDependencies, dependencies.current)) {
      fetched.current = false;
      resource.current = null;
      dependencies.current = propsDependencies;
      propsOnChange(null);
    }
  }, [propsDependencies, propsOnChange]);
  const fetch = async () => {
    var _a;
    if (fetched.current) {
      return;
    }
    if (props.saveOptions) {
      await props.saveOptions();
    }
    try {
      const resources2 = await ((_a = props.fetch) == null ? void 0 : _a.call(props)) || [];
      setResources(resources2);
    } finally {
      fetched.current = true;
    }
  };
  const onChange = (e) => {
    propsOnChange(e);
    if (e.value) {
      resource.current = e.value;
    }
  };
  const onClick = async () => {
    setIsLoading(true);
    try {
      await fetch();
    } finally {
      setIsLoading(false);
    }
  };
  return /* @__PURE__ */ React.createElement(
    Select,
    {
      ...props,
      id: props.id,
      inputId: props.id,
      "aria-label": props.label,
      options,
      onChange,
      isLoading,
      className: props.className || "min-width-6",
      onOpenMenu: () => props.fetch && onClick(),
      menuShouldPortal: true
    }
  );
}

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