import { jsx as n, jsxs as i, Fragment as y } from "react/jsx-runtime";
import { useState as F, useImperativeHandle as _, createElement as b } 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 v, TextField as K, Button as w } from "@mui/material";
import { getBlockletSDK as Q } from "@blocklet/js-sdk";
import T from "../Toast/index.js";
import Z from "../Dialog/dialog.js";
import "../Dialog/confirm.js";
import "lodash/noop";
import { OrgQueryType as J } from "../Util/client.js";
import { formatAxiosError as U } from "../Util/index.js";
import { translate as X } from "../Locale/util.js";
import Y from "./locales.js";
const I = 20;
function ue({
  ref: S,
  org: g,
  onSuccess: C,
  resourceId: f,
  locale: E = "en",
  dialogProps: k
}) {
  const o = p((e, r = {}) => X(Y, e, E, "en", r)), h = Q(), [x, c] = F(""), t = q({
    open: !1,
    selectedOrg: null
  }), O = G(x, { 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: O, type: J.OWNED }, R = await h.user.getOrgs(m), { orgs: j = [], paging: B } = R || {};
      return { list: j, total: B?.total || 0 };
    },
    {
      reloadDeps: [O],
      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("");
  }), D = 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 h.user.migrateResourceToOrg({ form: g.id, to: t.selectedOrg.id, resourceId: f }), s(), C?.(t.selectedOrg), T.success(o("tranferSuccess"));
    } catch (e) {
      console.error("Resource transfer failed", e), T.error(U(e));
    }
  });
  _(S, () => ({
    open: (e = {}) => {
      Object.assign(t, { open: !0, selectedOrg: null }, e), setTimeout(() => {
        t.open && z();
      }, 0);
    },
    close: s
  }));
  const M = 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(y, { children: [
        /* @__PURE__ */ n(w, { onClick: s, color: "secondary", variant: "outlined", children: o("cancel") }),
        /* @__PURE__ */ n(w, { onClick: D, 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: M,
            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 : x,
            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(
              K,
              {
                ...e,
                variant: "outlined",
                fullWidth: !0,
                InputProps: {
                  ...e.InputProps,
                  endAdornment: /* @__PURE__ */ i(y, { children: [
                    u && /* @__PURE__ */ n(v, { color: "inherit", size: 20 }),
                    e.InputProps.endAdornment
                  ] })
                }
              }
            ),
            renderOption: (e, r) => r.isLoadingItem ? /* @__PURE__ */ b(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(v, { size: 16, sx: { mr: 1 } }),
                  /* @__PURE__ */ n(a, { variant: "body2", sx: { fontStyle: d ? "italic" : "normal" }, children: r.name })
                ]
              }
            )) : /* @__PURE__ */ b(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 {
  ue as default
};
