import {
  useUserInviteTableQuery
} from "./chunk-BI2AYXZQ.js";
import "./chunk-MG4GKUJW.js";
import "./chunk-AYVH6Q5O.js";
import "./chunk-VOHEQ7B5.js";
import "./chunk-DY3XQPHC.js";
import "./chunk-GRH7C3QN.js";
import "./chunk-VKOE5J66.js";
import "./chunk-N3T24SEK.js";
import "./chunk-XBKWFLJG.js";
import {
  isFetchError
} from "./chunk-C6SUTRP2.js";
import "./chunk-BEPAXQMU.js";
import {
  KeyboundForm
} from "./chunk-SITRHMZZ.js";
import {
  RouteFocusModal
} from "./chunk-GDWBOQI5.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import "./chunk-FQERBIVS.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-7TQNE3E2.js";
import "./chunk-YN3FGNJM.js";
import "./chunk-KCHYLLVG.js";
import "./chunk-CVXKASWV.js";
import "./chunk-THHRRYRS.js";
import "./chunk-LRD242C7.js";
import {
  require_dist
} from "./chunk-52KJSIHS.js";
import "./chunk-INNFZYX2.js";
import "./chunk-QHQWEERJ.js";
import "./chunk-Y7QKP6QU.js";
import {
  useCreateInvite,
  useInvites
} from "./chunk-RLRWDHME.js";
import "./chunk-K5324KIX.js";
import "./chunk-FV76G2D7.js";
import "./chunk-GHDLST2P.js";
import "./chunk-YVYYOBAE.js";
import "./chunk-L2NJPDUD.js";
import "./chunk-P7UBW2EI.js";
import "./chunk-MR6REQKT.js";
import "./chunk-EPSDO2MJ.js";
import "./chunk-BHEU34FL.js";
import {
  useMe
} from "./chunk-W34KDYZA.js";
import "./chunk-II3CLUXA.js";
import "./chunk-XKEYHWBS.js";
import "./chunk-J2XUEO2E.js";
import "./chunk-656G74I2.js";
import "./chunk-VWPNMEOE.js";
import "./chunk-O72AIZUN.js";
import "./chunk-VUWAOX7H.js";
import "./chunk-5DKUSZQ7.js";
import "./chunk-DIAWPVYS.js";
import "./chunk-4U2BLH45.js";
import "./chunk-YAUGB4LD.js";
import "./chunk-A5DJIOHN.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-DTGEFKK4.js";
import {
  __toESM
} from "./chunk-NBMM2TZK.js";

// src/pages/settings/team/invite/_components/invite-user-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import i18n from "i18next";
import {
  Alert,
  Button,
  Container,
  Heading,
  Input,
  Select,
  StatusBadge,
  Text,
  Tooltip
} from "@medusajs/ui";
import { createColumnHelper } from "@tanstack/react-table";
import { format } from "date-fns";
import { useMemo } from "react";
import { useForm } from "react-hook-form";
import { Trans, useTranslation } from "react-i18next";
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 ROLE_LABEL_MAP = Object.fromEntries(
  ROLE_OPTIONS.map((r) => [r.value, r.labelKey])
);
var InviteUserSchema = zod.object({
  email: zod.string().email({ message: i18n.t("users.inviteForm.validation.emailInvalid") }),
  role_id: zod.string().min(1, { message: i18n.t("users.inviteForm.validation.roleRequired") })
});
var PAGE_SIZE = 10;
var PREFIX = "usr_invite";
var InviteUserForm = () => {
  const { t } = useTranslation();
  const { seller_member } = useMe();
  const sellerId = seller_member?.seller?.id;
  const form = useForm({
    defaultValues: {
      email: "",
      role_id: ""
    },
    resolver: zodResolver(InviteUserSchema)
  });
  const { raw, searchParams } = useUserInviteTableQuery({
    prefix: PREFIX,
    pageSize: PAGE_SIZE
  });
  const {
    member_invites,
    count,
    isPending: isLoading,
    isError,
    error
  } = useInvites(sellerId, searchParams);
  const columns = useColumns();
  const { table } = useDataTable({
    data: member_invites ?? [],
    columns,
    count,
    enablePagination: true,
    getRowId: (row) => row.id,
    pageSize: PAGE_SIZE,
    prefix: PREFIX
  });
  const { mutateAsync, isPending } = useCreateInvite(sellerId);
  const handleSubmit = form.handleSubmit(async (values) => {
    try {
      await mutateAsync({
        email: values.email,
        role_id: values.role_id
      });
      form.reset();
    } catch (error2) {
      if (isFetchError(error2) && error2.status === 400) {
        form.setError("root", {
          type: "manual",
          message: error2.message
        });
        return;
      }
    }
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx(RouteFocusModal.Form, { form, children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex h-full flex-col overflow-hidden",
      children: [
        /* @__PURE__ */ jsx(RouteFocusModal.Header, {}),
        /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "flex flex-1 flex-col overflow-hidden", children: /* @__PURE__ */ jsx("div", { className: "flex flex-1 flex-col items-center overflow-y-auto", children: /* @__PURE__ */ jsxs("div", { className: "flex w-full max-w-[720px] flex-col gap-y-8 px-2 py-16", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Heading, { children: t("users.inviteUser") }),
            /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: t("users.inviteUserHint") })
          ] }),
          form.formState.errors.root && /* @__PURE__ */ jsx(
            Alert,
            {
              variant: "error",
              dismissible: false,
              className: "text-balance",
              children: form.formState.errors.root.message
            }
          ),
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
            /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-4", children: [
              /* @__PURE__ */ jsx(
                Form.Field,
                {
                  control: form.control,
                  name: "email",
                  render: ({ field }) => {
                    return /* @__PURE__ */ jsxs(Form.Item, { children: [
                      /* @__PURE__ */ jsx(Form.Label, { children: t("fields.email") }),
                      /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { ...field }) }),
                      /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                    ] });
                  }
                }
              ),
              /* @__PURE__ */ jsx(
                Form.Field,
                {
                  control: form.control,
                  name: "role_id",
                  render: ({ field: { onChange, ref, ...field } }) => {
                    return /* @__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("users.selectRole")
                          }
                        ) }),
                        /* @__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("div", { className: "flex items-center justify-end", children: /* @__PURE__ */ jsx(
              Button,
              {
                size: "small",
                variant: "secondary",
                type: "submit",
                isLoading: isPending,
                children: t("users.sendInvite")
              }
            ) })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
            /* @__PURE__ */ jsx(Heading, { level: "h2", children: t("users.pendingInvites") }),
            /* @__PURE__ */ jsx(Container, { className: "overflow-hidden p-0", children: /* @__PURE__ */ jsx(
              _DataTable,
              {
                table,
                columns,
                count,
                pageSize: PAGE_SIZE,
                pagination: true,
                isLoading,
                queryObject: raw,
                prefix: PREFIX,
                orderBy: [
                  { key: "email", label: t("fields.email") },
                  {
                    key: "created_at",
                    label: t("fields.createdAt")
                  }
                ]
              }
            ) })
          ] })
        ] }) }) })
      ]
    }
  ) });
};
var columnHelper = createColumnHelper();
var useColumns = () => {
  const { t } = useTranslation();
  return useMemo(
    () => [
      columnHelper.accessor("email", {
        header: t("fields.email"),
        cell: ({ getValue }) => getValue()
      }),
      columnHelper.accessor("role_id", {
        header: t("fields.role"),
        cell: ({ getValue }) => {
          const roleId = getValue();
          const labelKey = ROLE_LABEL_MAP[roleId];
          return labelKey ? t(labelKey) : "-";
        }
      }),
      columnHelper.accessor("accepted", {
        header: t("fields.status"),
        cell: ({ getValue, row }) => {
          const accepted = getValue();
          const expired = new Date(row.original.expires_at) < /* @__PURE__ */ new Date();
          if (accepted) {
            return /* @__PURE__ */ jsx(
              Tooltip,
              {
                content: t("users.acceptedOnDate", {
                  date: format(
                    new Date(row.original.updated_at),
                    "dd MMM, yyyy"
                  )
                }),
                children: /* @__PURE__ */ jsx(StatusBadge, { color: "green", children: t("users.inviteStatus.accepted") })
              }
            );
          }
          if (expired) {
            return /* @__PURE__ */ jsx(
              Tooltip,
              {
                content: t("users.expiredOnDate", {
                  date: format(
                    new Date(row.original.expires_at),
                    "dd MMM, yyyy"
                  )
                }),
                children: /* @__PURE__ */ jsx(StatusBadge, { color: "red", children: t("users.inviteStatus.expired") })
              }
            );
          }
          return /* @__PURE__ */ jsx(
            Tooltip,
            {
              content: /* @__PURE__ */ jsx(
                Trans,
                {
                  i18nKey: "users.validFromUntil",
                  components: [
                    /* @__PURE__ */ jsx("span", { className: "font-medium" }, "from"),
                    /* @__PURE__ */ jsx("span", { className: "font-medium" }, "until")
                  ],
                  values: {
                    from: format(
                      new Date(row.original.created_at),
                      "dd MMM, yyyy"
                    ),
                    until: format(
                      new Date(row.original.expires_at),
                      "dd MMM, yyyy"
                    )
                  }
                }
              ),
              children: /* @__PURE__ */ jsx(StatusBadge, { color: "orange", children: t("users.inviteStatus.pending") })
            }
          );
        }
      })
    ],
    [t]
  );
};

// src/pages/settings/team/invite/index.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var TeamInvite = () => {
  return /* @__PURE__ */ jsx2(RouteFocusModal, { children: /* @__PURE__ */ jsx2(InviteUserForm, {}) });
};
export {
  TeamInvite
};
