"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import React from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Button } from "@open-mercato/ui/primitives/button";
import { Input } from "@open-mercato/ui/primitives/input";
import { EmailInput } from "@open-mercato/ui/primitives/email-input";
import { StatusBadge } from "@open-mercato/ui/primitives/status-badge";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
function InviteForm({ personEntityId, onSuccess }) {
  const t = useT();
  const [isLoadingPerson, setIsLoadingPerson] = React.useState(true);
  const [email, setEmail] = React.useState("");
  const [displayName, setDisplayName] = React.useState("");
  const [selectedRoleIds, setSelectedRoleIds] = React.useState([]);
  const [availableRoles, setAvailableRoles] = React.useState([]);
  const [isLoadingRoles, setIsLoadingRoles] = React.useState(true);
  const [isSubmitting, setIsSubmitting] = React.useState(false);
  const { runMutation } = useGuardedMutation({
    contextId: "customer_accounts:account-status-invite"
  });
  React.useEffect(() => {
    let cancelled = false;
    async function loadPerson() {
      try {
        const call = await apiCall(
          `/api/customers/people/${encodeURIComponent(personEntityId)}`
        );
        if (cancelled) return;
        if (call.ok && call.result) {
          const person = call.result.person;
          const profile = call.result.profile;
          if (person?.primaryEmail) {
            setEmail(person.primaryEmail);
          }
          const nameParts = [profile?.firstName, profile?.lastName].filter(Boolean);
          if (nameParts.length > 0) {
            setDisplayName(nameParts.join(" "));
          } else if (person?.displayName) {
            setDisplayName(person.displayName);
          }
        }
      } catch {
      } finally {
        if (!cancelled) setIsLoadingPerson(false);
      }
    }
    loadPerson();
    return () => {
      cancelled = true;
    };
  }, [personEntityId]);
  React.useEffect(() => {
    let cancelled = false;
    async function loadRoles() {
      try {
        const call = await apiCall(
          "/api/customer_accounts/admin/roles?pageSize=100"
        );
        if (cancelled) return;
        if (call.ok && call.result) {
          const items = Array.isArray(call.result.items) ? call.result.items : [];
          setAvailableRoles(items.map((role) => ({ id: role.id, name: role.name })));
        }
      } catch {
      } finally {
        if (!cancelled) setIsLoadingRoles(false);
      }
    }
    loadRoles();
    return () => {
      cancelled = true;
    };
  }, []);
  function toggleRole(roleId) {
    setSelectedRoleIds(
      (prev) => prev.includes(roleId) ? prev.filter((id) => id !== roleId) : [...prev, roleId]
    );
  }
  async function handleSubmit() {
    const trimmedEmail = email.trim();
    if (!trimmedEmail) {
      flash(t("customer_accounts.widgets.invite.error.emailRequired", "Email is required"), "error");
      return;
    }
    if (selectedRoleIds.length === 0) {
      flash(t("customer_accounts.widgets.invite.error.roleRequired", "At least one role must be selected"), "error");
      return;
    }
    setIsSubmitting(true);
    try {
      await runMutation({
        context: { entityType: "customer_accounts:user" },
        mutationPayload: { customerEntityId: personEntityId, roleIds: selectedRoleIds },
        operation: async () => {
          const call = await apiCall(
            "/api/customer_accounts/admin/users-invite",
            {
              method: "POST",
              headers: { "content-type": "application/json" },
              body: JSON.stringify({
                email: trimmedEmail,
                roleIds: selectedRoleIds,
                displayName: displayName.trim() || void 0,
                customerEntityId: personEntityId
              })
            }
          );
          if (!call.ok) {
            const errorMessage = call.result?.error;
            flash(errorMessage || t("customer_accounts.widgets.invite.error.failed", "Failed to send invitation"), "error");
            return;
          }
          flash(t("customer_accounts.widgets.invite.success", "Invitation sent successfully"), "success");
          onSuccess();
        }
      });
    } catch {
      flash(t("customer_accounts.widgets.invite.error.failed", "Failed to send invitation"), "error");
    } finally {
      setIsSubmitting(false);
    }
  }
  const isLoading = isLoadingPerson || isLoadingRoles;
  if (isLoading) {
    return /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground py-2", children: t("common.loading", "Loading...") });
  }
  return /* @__PURE__ */ jsxs("div", { className: "space-y-3 mt-2", children: [
    /* @__PURE__ */ jsxs("div", { children: [
      /* @__PURE__ */ jsx("label", { htmlFor: "invite-email", className: "block text-xs font-medium text-muted-foreground mb-1", children: t("common.email", "Email") }),
      /* @__PURE__ */ jsx(
        EmailInput,
        {
          id: "invite-email",
          size: "sm",
          value: email,
          onChange: (event) => setEmail(event.target.value),
          required: true,
          disabled: isSubmitting
        }
      )
    ] }),
    /* @__PURE__ */ jsxs("div", { children: [
      /* @__PURE__ */ jsx("label", { htmlFor: "invite-display-name", className: "block text-xs font-medium text-muted-foreground mb-1", children: t("customer_accounts.widgets.invite.displayName", "Display Name") }),
      /* @__PURE__ */ jsx(
        Input,
        {
          id: "invite-display-name",
          type: "text",
          size: "sm",
          value: displayName,
          onChange: (event) => setDisplayName(event.target.value),
          disabled: isSubmitting
        }
      )
    ] }),
    /* @__PURE__ */ jsxs("div", { children: [
      /* @__PURE__ */ jsx("div", { className: "text-xs font-medium text-muted-foreground mb-1.5", children: t("customer_accounts.widgets.invite.roles", "Roles") }),
      availableRoles.length === 0 ? /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground", children: t("customer_accounts.widgets.invite.noRoles", "No roles available") }) : /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1.5", children: availableRoles.map((role) => /* @__PURE__ */ jsx(
        Button,
        {
          type: "button",
          variant: selectedRoleIds.includes(role.id) ? "default" : "outline",
          size: "sm",
          onClick: () => toggleRole(role.id),
          disabled: isSubmitting,
          className: "text-xs h-7",
          children: role.name
        },
        role.id
      )) })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "flex justify-end gap-2 pt-1", children: /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        size: "sm",
        onClick: handleSubmit,
        disabled: isSubmitting || !email.trim() || selectedRoleIds.length === 0,
        children: isSubmitting ? t("common.loading", "Loading...") : t("customer_accounts.widgets.invite.submit", "Send Invitation")
      }
    ) })
  ] });
}
function AccountStatusWidget({ context }) {
  const t = useT();
  const queryClient = useQueryClient();
  const personEntityId = context?.recordId;
  const [showInviteForm, setShowInviteForm] = React.useState(false);
  const { data, isLoading } = useQuery({
    queryKey: ["customer-account-status", personEntityId],
    queryFn: async () => {
      if (!personEntityId) return null;
      const result = await apiCall(`/api/customer_accounts/admin/users?personEntityId=${personEntityId}&pageSize=1`);
      if (!result.ok) return null;
      const json = result.result;
      const items = json?.items;
      return items?.[0] || null;
    },
    enabled: !!personEntityId
  });
  function handleInviteSuccess() {
    setShowInviteForm(false);
    queryClient.invalidateQueries({ queryKey: ["customer-account-status", personEntityId] });
  }
  if (isLoading) {
    return /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground", children: t("common.loading", "Loading...") });
  }
  if (!data) {
    return /* @__PURE__ */ jsxs("div", { className: "rounded-md border p-3", children: [
      /* @__PURE__ */ jsx("div", { className: "text-sm font-medium mb-1", children: t("customer_accounts.widgets.accountStatus", "Portal Account") }),
      /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground", children: t("customer_accounts.widgets.noAccount", "No portal account linked") }),
      !showInviteForm && personEntityId && /* @__PURE__ */ jsx("div", { className: "mt-2", children: /* @__PURE__ */ jsx(
        Button,
        {
          type: "button",
          variant: "outline",
          size: "sm",
          onClick: () => setShowInviteForm(true),
          children: t("customer_accounts.widgets.invite.button", "Invite to Portal")
        }
      ) }),
      showInviteForm && personEntityId && /* @__PURE__ */ jsx(InviteForm, { personEntityId, onSuccess: handleInviteSuccess })
    ] });
  }
  return /* @__PURE__ */ jsxs("div", { className: "rounded-md border p-3", children: [
    /* @__PURE__ */ jsx("div", { className: "text-sm font-medium mb-2", children: t("customer_accounts.widgets.accountStatus", "Portal Account") }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-1 text-sm", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
        /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: t("common.status", "Status") }),
        /* @__PURE__ */ jsx(StatusBadge, { variant: data.isActive ? "success" : "error", dot: true, children: data.isActive ? t("common.active", "Active") : t("common.inactive", "Inactive") })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
        /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: t("common.email", "Email") }),
        /* @__PURE__ */ jsx("span", { children: data.email })
      ] }),
      data.emailVerified !== void 0 && /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
        /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: t("customer_accounts.widgets.emailVerified", "Email Verified") }),
        /* @__PURE__ */ jsx("span", { children: data.emailVerified ? "\u2713" : "\u2717" })
      ] }),
      data.lastLoginAt && /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
        /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: t("customer_accounts.widgets.lastLogin", "Last Login") }),
        /* @__PURE__ */ jsx("span", { children: new Date(data.lastLoginAt).toLocaleDateString() })
      ] })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "mt-2", children: /* @__PURE__ */ jsx(
      "a",
      {
        href: `/backend/customer_accounts/users/${data.id}`,
        className: "text-xs text-primary hover:underline",
        children: t("customer_accounts.widgets.viewAccount", "View account details \u2192")
      }
    ) })
  ] });
}
export {
  AccountStatusWidget as default
};
//# sourceMappingURL=widget.client.js.map
