import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import {
  require_dist
} from "./chunk-ZZO3INVE.js";
import {
  RouteDrawer,
  useRouteModal
} from "./chunk-FWJLS7XD.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  useMembers
} from "./chunk-WJJXUXSO.js";
import {
  useAddSellerMember,
  useInviteSellerMember,
  useSellerInvites,
  useSellerMembers
} from "./chunk-LEG67A2R.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-ZBWL72TB.js";
import {
  __toESM
} from "./chunk-NBMM2TZK.js";

// src/pages/stores/store-member-invite/index.tsx
import { Heading } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";

// src/pages/stores/store-member-invite/components/invite-member-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import i18n from "i18next";
import { Button, Input, Select, Text, clx, toast } from "@medusajs/ui";
import { useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { useParams } from "react-router-dom";
import * as zod from "zod";
var import_types = __toESM(require_dist(), 1);
import { jsx, jsxs } from "react/jsx-runtime";
var ROLE_OPTIONS = [
  {
    value: import_types.SellerRole.SELLER_ADMINISTRATION,
    labelKey: "users.roles.administration"
  },
  {
    value: import_types.SellerRole.INVENTORY_MANAGEMENT,
    labelKey: "users.roles.inventoryManagement"
  },
  {
    value: import_types.SellerRole.ORDER_MANAGEMENT,
    labelKey: "users.roles.orderManagement"
  },
  { value: import_types.SellerRole.ACCOUNTING, labelKey: "users.roles.accounting" },
  { value: import_types.SellerRole.SUPPORT, labelKey: "users.roles.support" }
];
var InviteMemberSchema = zod.object({
  email: zod.string().min(1, { message: i18n.t("stores.create.validation.emailRequired") }).email({ message: i18n.t("stores.create.validation.emailInvalid") }),
  role_id: zod.string().min(1, { message: i18n.t("stores.members.addUser.validation.roleRequired") })
});
var InviteMemberForm = () => {
  const { t } = useTranslation();
  const { id } = useParams();
  const { handleSuccess } = useRouteModal();
  const [suggestionsOpen, setSuggestionsOpen] = useState(false);
  const form = useForm({
    defaultValues: {
      email: "",
      role_id: ""
    },
    mode: "onSubmit",
    reValidateMode: "onSubmit",
    resolver: zodResolver(InviteMemberSchema)
  });
  const emailValue = form.watch("email");
  const { members } = useMembers(
    { q: emailValue || void 0, limit: 10 },
    { placeholderData: (prev) => prev }
  );
  const { seller_members: currentMembers } = useSellerMembers(id, {
    limit: 100,
    offset: 0
  });
  const { member_invites: pendingInvites } = useSellerInvites(id);
  const existingEmails = useMemo(() => {
    const emails = /* @__PURE__ */ new Set();
    (currentMembers ?? []).forEach((sm) => {
      const email = sm.member?.email;
      if (email) {
        emails.add(email.toLowerCase());
      }
    });
    (pendingInvites ?? []).filter((invite) => !invite.accepted).forEach((invite) => {
      if (invite.email) {
        emails.add(invite.email.toLowerCase());
      }
    });
    return emails;
  }, [currentMembers, pendingInvites]);
  const memberList = useMemo(() => {
    const all = members ?? [];
    return all.filter(
      (m) => !existingEmails.has(m.email.toLowerCase())
    );
  }, [members, existingEmails]);
  const { mutateAsync: inviteMember, isPending: isInviting } = useInviteSellerMember(id);
  const { mutateAsync: addMember, isPending: isAdding } = useAddSellerMember(
    id
  );
  const isPending = isInviting || isAdding;
  const handleSubmit = form.handleSubmit(async (values) => {
    try {
      const matched = memberList.find(
        (m) => m.email.toLowerCase() === values.email.toLowerCase()
      );
      if (matched) {
        await addMember({
          member_id: matched.id,
          role_id: values.role_id
        });
        toast.success(t("stores.members.addUser.addedToast"));
      } else {
        await inviteMember({
          email: values.email,
          role_id: values.role_id
        });
        toast.success(t("stores.members.addUser.invitedToast"));
      }
      handleSuccess();
    } catch (error) {
      toast.error(error.message);
    }
  });
  return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex flex-1 flex-col overflow-hidden",
      children: [
        /* @__PURE__ */ jsxs(RouteDrawer.Body, { className: "flex flex-col gap-y-6 overflow-y-auto", children: [
          /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: t("stores.members.addUser.hint") }),
          /* @__PURE__ */ jsx(
            Form.Field,
            {
              control: form.control,
              name: "email",
              render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                /* @__PURE__ */ jsx(Form.Label, { children: t("fields.email") }),
                /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsxs("div", { className: "relative", children: [
                  /* @__PURE__ */ jsx(
                    Input,
                    {
                      ...field,
                      autoComplete: "off",
                      onFocus: () => setSuggestionsOpen(true),
                      onBlur: () => {
                        field.onBlur();
                        setTimeout(() => setSuggestionsOpen(false), 150);
                      }
                    }
                  ),
                  suggestionsOpen && memberList.length > 0 && /* @__PURE__ */ jsx(
                    "div",
                    {
                      className: clx(
                        "bg-ui-bg-base shadow-elevation-flyout border-ui-border-base absolute z-50 mt-1 flex max-h-60 w-full flex-col overflow-y-auto rounded-md border p-1"
                      ),
                      children: memberList.map((member) => /* @__PURE__ */ jsx(
                        "button",
                        {
                          type: "button",
                          onMouseDown: (e) => {
                            e.preventDefault();
                            field.onChange(member.email);
                            setSuggestionsOpen(false);
                          },
                          className: "hover:bg-ui-bg-base-hover text-ui-fg-base flex w-full items-center rounded-sm px-2 py-1.5 text-left text-sm",
                          children: member.email
                        },
                        member.id
                      ))
                    }
                  )
                ] }) }),
                /* @__PURE__ */ jsx(Form.ErrorMessage, {})
              ] })
            }
          ),
          /* @__PURE__ */ jsx(
            Form.Field,
            {
              control: form.control,
              name: "role_id",
              render: ({ field: { onChange, ref, ...field } }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                /* @__PURE__ */ jsx(Form.Label, { children: t("fields.role") }),
                /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsxs(Select, { ...field, onValueChange: onChange, children: [
                  /* @__PURE__ */ jsx(Select.Trigger, { ref, children: /* @__PURE__ */ jsx(Select.Value, { placeholder: t("fields.selectPlaceholder", "Select") }) }),
                  /* @__PURE__ */ jsx(Select.Content, { children: ROLE_OPTIONS.map((role) => /* @__PURE__ */ jsx(Select.Item, { value: role.value, children: t(role.labelKey) }, role.value)) })
                ] }) }),
                /* @__PURE__ */ jsx(Form.ErrorMessage, {})
              ] })
            }
          )
        ] }),
        /* @__PURE__ */ jsx(RouteDrawer.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
          /* @__PURE__ */ jsx(RouteDrawer.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", type: "button", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx(Button, { size: "small", type: "submit", isLoading: isPending, children: t("actions.save") })
        ] }) })
      ]
    }
  ) });
};

// src/pages/stores/store-member-invite/index.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var Root = () => {
  const { t } = useTranslation2();
  return /* @__PURE__ */ jsxs2(RouteDrawer, { children: [
    /* @__PURE__ */ jsx2(RouteDrawer.Header, { children: /* @__PURE__ */ jsx2(Heading, { children: t("stores.members.addUser.header") }) }),
    /* @__PURE__ */ jsx2(InviteMemberForm, {})
  ] });
};
var Component = Root;
export {
  Component
};
