import { jsx as n, jsxs as i, Fragment as O } from "react/jsx-runtime";
import { useState as F, useImperativeHandle as _, createElement as y } from "react";
import { useMemoizedFn as p, useReactive as q, useDebounce as G, useInfiniteScroll as H } from "ahooks";
import { Box as l, Typography as a, Autocomplete as N, CircularProgress as b, TextField as Q, Button as v } from "@mui/material";
import w from "../Toast/index.js";
import Z from "../Dialog/dialog.js";
import "../Dialog/confirm.js";
import "lodash/noop";
import { OrgQueryType as J, client as T } from "../Util/client.js";
import { formatAxiosError as K } from "../Util/index.js";
import { translate as U } from "../Locale/util.js";
import X from "./locales.js";
const I = 20;
function ce({
  ref: C,
  org: g,
  onSuccess: S,
  resourceId: f,
  locale: E = "en",
  dialogProps: k
}) {
  const o = p((e, r = {}) => U(X, e, E, "en", r)), [h, c] = F(""), t = q({
    open: !1,
    selectedOrg: null
  }), x = G(h, { wait: 500 }), { data: A, loadMore: W, loadingMore: d, loading: u, reload: z } = H(
    async (e) => {
      if (!t.open) return { list: [], total: 0 };
      const m = { page: e ? Math.ceil(e.list.length / I) + 1 : 1, pageSize: I, search: x, type: J.OWNED }, R = await T.user.getOrgs(m), { orgs: j = [], paging: B } = R || {};
      return { list: j, total: B?.total || 0 };
    },
    {
      reloadDeps: [x],
      isNoMore: (e) => e?.list.length ? e.list.length >= e?.total : !0,
      onError: (e) => {
        console.error("Get orgs failed", e);
      },
      manual: !0
      // 手动触发，在对话框打开时再加载
    }
  ), s = p(() => {
    t.open = !1, t.selectedOrg = null, c("");
  }), M = p(async () => {
    try {
      if (!f)
        throw new Error(o("resourceIdRequired"));
      if (!t.selectedOrg)
        throw new Error(o("placeholder"));
      if (t.selectedOrg.id === g.id)
        throw new Error(o("organizationSameAsCurrent"));
      await T.user.migrateResourceToOrg({ form: g.id, to: t.selectedOrg.id, resourceId: f }), s(), S?.(t.selectedOrg), w.success(o("tranferSuccess"));
    } catch (e) {
      console.error("Resource transfer failed", e), w.error(K(e));
    }
  });
  _(C, () => ({
    open: (e = {}) => {
      Object.assign(t, { open: !0, selectedOrg: null }, e), setTimeout(() => {
        t.open && z();
      }, 0);
    },
    close: s
  }));
  const D = A?.list || [], { placeholder: L = "", ...P } = k || {};
  return /* @__PURE__ */ n(
    Z,
    {
      title: o("transferOrg"),
      fullWidth: !0,
      maxWidth: "sm",
      open: t.open,
      onClose: s,
      actions: /* @__PURE__ */ i(O, { children: [
        /* @__PURE__ */ n(v, { onClick: s, color: "secondary", variant: "outlined", children: o("cancel") }),
        /* @__PURE__ */ n(v, { onClick: M, color: "primary", variant: "contained", disabled: !t.selectedOrg, children: o("confirm") })
      ] }),
      ...P || {},
      children: /* @__PURE__ */ i(l, { children: [
        /* @__PURE__ */ n(a, { variant: "body2", color: "text.secondary", sx: { mb: 2 }, children: L || o("placeholder") }),
        /* @__PURE__ */ n(
          N,
          {
            options: D,
            getOptionLabel: (e) => e?.name || "",
            isOptionEqualToValue: (e, r) => e?.id === r?.id,
            value: t.selectedOrg,
            onChange: (e, r) => {
              if (r?.isLoadingItem && !d) {
                W();
                return;
              }
              r?.isLoadingItem || (t.selectedOrg = r, r && c(""));
            },
            inputValue: t.selectedOrg ? t.selectedOrg.name : h,
            onInputChange: (e, r, m) => {
              m === "input" && (t.selectedOrg && (t.selectedOrg = null), c(r));
            },
            loading: u,
            loadingText: o("loading"),
            noOptionsText: o(u ? "loading" : "noResults"),
            renderInput: (e) => /* @__PURE__ */ n(
              Q,
              {
                ...e,
                variant: "outlined",
                fullWidth: !0,
                InputProps: {
                  ...e.InputProps,
                  endAdornment: /* @__PURE__ */ i(O, { children: [
                    u && /* @__PURE__ */ n(b, { color: "inherit", size: 20 }),
                    e.InputProps.endAdornment
                  ] })
                }
              }
            ),
            renderOption: (e, r) => r.isLoadingItem ? /* @__PURE__ */ y(l, { component: "li", ...e, key: r.id }, /* @__PURE__ */ i(
              l,
              {
                sx: {
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  flex: 1,
                  py: 1,
                  color: "primary.main",
                  cursor: "pointer"
                },
                children: [
                  d && /* @__PURE__ */ n(b, { size: 16, sx: { mr: 1 } }),
                  /* @__PURE__ */ n(a, { variant: "body2", sx: { fontStyle: d ? "italic" : "normal" }, children: r.name })
                ]
              }
            )) : /* @__PURE__ */ y(l, { component: "li", ...e, key: r.id }, /* @__PURE__ */ i(l, { sx: { display: "flex", flexDirection: "column", flex: 1, minWidth: 0 }, children: [
              /* @__PURE__ */ n(
                a,
                {
                  variant: "body1",
                  sx: {
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap"
                  },
                  children: r.name
                }
              ),
              r.description && /* @__PURE__ */ n(
                a,
                {
                  variant: "body2",
                  color: "text.secondary",
                  sx: {
                    display: "-webkit-box",
                    WebkitLineClamp: 3,
                    WebkitBoxOrient: "vertical",
                    overflow: "hidden",
                    textOverflow: "ellipsis"
                  },
                  children: r.description
                }
              )
            ] })),
            sx: {
              "& .MuiAutocomplete-listbox": {
                maxHeight: 200
              }
            }
          }
        )
      ] })
    }
  );
}
export {
  ce as default
};
