"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Globe, Settings } from "lucide-react";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { DataTable } from "@open-mercato/ui/backend/DataTable";
import { RowActions } from "@open-mercato/ui/backend/RowActions";
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 { PasswordInput } from "@open-mercato/ui/primitives/password-input";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@open-mercato/ui/primitives/dialog";
import { apiCall, readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { ListEmptyState } from "@open-mercato/ui/backend/filters/ListEmptyState";
function formatDate(value, fallback) {
  if (!value) return fallback;
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return fallback;
  return date.toLocaleDateString();
}
async function fetchRoleFilterOptions() {
  try {
    const call = await apiCall(
      "/api/customer_accounts/admin/roles?pageSize=100"
    );
    if (!call.ok) return [];
    const items = Array.isArray(call.result?.items) ? call.result.items : [];
    return items.filter((item) => typeof item?.id === "string" && typeof item?.name === "string").map((item) => ({ value: item.id, label: item.name, id: item.id }));
  } catch {
    return [];
  }
}
function CreateUserDialog({
  open,
  onOpenChange,
  roleOptions,
  onCreated,
  onRunMutation
}) {
  const t = useT();
  const [email, setEmail] = React.useState("");
  const [displayName, setDisplayName] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [selectedRoleIds, setSelectedRoleIds] = React.useState([]);
  const [isSubmitting, setIsSubmitting] = React.useState(false);
  const resetForm = React.useCallback(() => {
    setEmail("");
    setDisplayName("");
    setPassword("");
    setSelectedRoleIds([]);
  }, []);
  const handleSubmit = React.useCallback(async (event) => {
    event.preventDefault();
    if (!email.trim() || !displayName.trim() || !password.trim()) {
      flash(t("customer_accounts.admin.createUser.error.required", "Email, name, and password are required"), "error");
      return;
    }
    setIsSubmitting(true);
    try {
      await onRunMutation(async () => {
        const call = await apiCall(
          "/api/customer_accounts/admin/users",
          {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify({
              email: email.trim(),
              displayName: displayName.trim(),
              password,
              roleIds: selectedRoleIds.length > 0 ? selectedRoleIds : void 0
            })
          }
        );
        if (!call.ok) {
          flash(call.result?.error || t("customer_accounts.admin.createUser.error.save", "Failed to create user"), "error");
          return;
        }
        flash(t("customer_accounts.admin.createUser.flash.created", "User created"), "success");
        resetForm();
        onOpenChange(false);
        onCreated();
      });
    } catch (err) {
      const message = err instanceof Error ? err.message : t("customer_accounts.admin.createUser.error.save", "Failed to create user");
      flash(message, "error");
    } finally {
      setIsSubmitting(false);
    }
  }, [displayName, email, onCreated, onOpenChange, onRunMutation, password, resetForm, selectedRoleIds, t]);
  const handleKeyDown = React.useCallback((event) => {
    if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
      event.preventDefault();
      const form = event.target.closest("form");
      if (form) form.requestSubmit();
    }
  }, []);
  return /* @__PURE__ */ jsx(Dialog, { open, onOpenChange: (next) => {
    if (!next) resetForm();
    onOpenChange(next);
  }, children: /* @__PURE__ */ jsxs(DialogContent, { className: "sm:max-w-lg", children: [
    /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: t("customer_accounts.admin.createUser.title", "Create Customer User") }) }),
    /* @__PURE__ */ jsxs("form", { onSubmit: (event) => {
      void handleSubmit(event);
    }, onKeyDown: handleKeyDown, className: "space-y-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx("label", { className: "text-sm font-medium", htmlFor: "create-email", children: t("customer_accounts.admin.createUser.fields.email", "Email") }),
        /* @__PURE__ */ jsx(
          EmailInput,
          {
            id: "create-email",
            required: true,
            value: email,
            onChange: (event) => setEmail(event.target.value),
            placeholder: t("customer_accounts.admin.createUser.fields.emailPlaceholder", "user@example.com")
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx("label", { className: "text-sm font-medium", htmlFor: "create-name", children: t("customer_accounts.admin.createUser.fields.displayName", "Display Name") }),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: "create-name",
            type: "text",
            required: true,
            value: displayName,
            onChange: (event) => setDisplayName(event.target.value),
            placeholder: t("customer_accounts.admin.createUser.fields.displayNamePlaceholder", "John Doe")
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx("label", { className: "text-sm font-medium", htmlFor: "create-password", children: t("customer_accounts.admin.createUser.fields.password", "Password") }),
        /* @__PURE__ */ jsx(
          PasswordInput,
          {
            id: "create-password",
            required: true,
            minLength: 8,
            value: password,
            onChange: (event) => setPassword(event.target.value),
            placeholder: t("customer_accounts.admin.createUser.fields.passwordPlaceholder", "Min. 8 characters"),
            autoComplete: "new-password"
          }
        )
      ] }),
      roleOptions.length > 0 && /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: t("customer_accounts.admin.createUser.fields.roles", "Roles") }),
        /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2", children: roleOptions.map((role) => {
          const isSelected = selectedRoleIds.includes(role.id);
          return /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              size: "2xs",
              variant: isSelected ? "secondary" : "outline",
              "aria-pressed": isSelected,
              onClick: () => setSelectedRoleIds(
                (prev) => prev.includes(role.id) ? prev.filter((rid) => rid !== role.id) : [...prev, role.id]
              ),
              className: "rounded-full",
              children: role.label
            },
            role.id
          );
        }) })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex justify-end gap-2 pt-2", children: [
        /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: () => {
          resetForm();
          onOpenChange(false);
        }, children: t("customer_accounts.admin.createUser.actions.cancel", "Cancel") }),
        /* @__PURE__ */ jsx(Button, { type: "submit", disabled: isSubmitting, children: isSubmitting ? t("customer_accounts.admin.createUser.actions.creating", "Creating...") : t("customer_accounts.admin.createUser.actions.create", "Create User") })
      ] })
    ] })
  ] }) });
}
function CustomerAccountsPage() {
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const t = useT();
  const router = useRouter();
  const [rows, setRows] = React.useState([]);
  const [page, setPage] = React.useState(1);
  const [pageSize] = React.useState(50);
  const [total, setTotal] = React.useState(0);
  const [totalPages, setTotalPages] = React.useState(1);
  const [search, setSearch] = React.useState("");
  const [filterValues, setFilterValues] = React.useState({});
  const [isLoading, setIsLoading] = React.useState(true);
  const [reloadToken, setReloadToken] = React.useState(0);
  const [roleOptions, setRoleOptions] = React.useState([]);
  const [createDialogOpen, setCreateDialogOpen] = React.useState(false);
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: "customer_accounts:users-list"
  });
  const runMutationWithContext = React.useCallback(
    async (operation, mutationPayload) => {
      return runMutation({
        operation,
        mutationPayload,
        context: { entityType: "customer_accounts:user" }
      });
    },
    [runMutation]
  );
  React.useEffect(() => {
    let cancelled = false;
    fetchRoleFilterOptions().then((opts) => {
      if (!cancelled) setRoleOptions(opts);
    });
    return () => {
      cancelled = true;
    };
  }, []);
  const filters = React.useMemo(() => [
    {
      id: "status",
      label: t("customer_accounts.admin.filters.status", "Status"),
      type: "select",
      options: [
        { value: "active", label: t("customer_accounts.admin.filters.active", "Active") },
        { value: "inactive", label: t("customer_accounts.admin.filters.inactive", "Inactive") }
      ]
    },
    {
      id: "roleId",
      label: t("customer_accounts.admin.filters.role", "Role"),
      type: "select",
      options: roleOptions
    }
  ], [roleOptions, t]);
  const queryParams = React.useMemo(() => {
    const params = new URLSearchParams();
    params.set("page", String(page));
    params.set("pageSize", String(pageSize));
    if (search.trim()) params.set("search", search.trim());
    const status = filterValues.status;
    if (typeof status === "string" && status.trim()) params.set("status", status);
    const roleId = filterValues.roleId;
    if (typeof roleId === "string" && roleId.trim()) params.set("roleId", roleId);
    return params.toString();
  }, [filterValues, page, pageSize, search]);
  React.useEffect(() => {
    let cancelled = false;
    async function load() {
      setIsLoading(true);
      try {
        const fallback = { items: [], total: 0, totalPages: 1 };
        const payload = await readApiResultOrThrow(
          `/api/customer_accounts/admin/users?${queryParams}`,
          void 0,
          { errorMessage: t("customer_accounts.admin.error.loadUsers", "Failed to load customer users"), fallback }
        );
        if (cancelled) return;
        const items = Array.isArray(payload?.items) ? payload.items : [];
        setRows(items);
        setTotal(typeof payload?.total === "number" ? payload.total : items.length);
        setTotalPages(typeof payload?.totalPages === "number" ? payload.totalPages : 1);
      } catch (err) {
        if (!cancelled) {
          const message = err instanceof Error ? err.message : t("customer_accounts.admin.error.loadUsers", "Failed to load customer users");
          flash(message, "error");
        }
      } finally {
        if (!cancelled) setIsLoading(false);
      }
    }
    load();
    return () => {
      cancelled = true;
    };
  }, [queryParams, reloadToken, t]);
  const handleToggleActive = React.useCallback(async (user) => {
    const nextActive = !user.isActive;
    const actionLabel = nextActive ? t("customer_accounts.admin.actions.activate", "Activate") : t("customer_accounts.admin.actions.deactivate", "Deactivate");
    const confirmed = await confirm({
      title: t("customer_accounts.admin.confirm.toggleActive", '{{action}} user "{{name}}"?', {
        action: actionLabel,
        name: user.displayName || user.email
      }),
      variant: nextActive ? "default" : "destructive"
    });
    if (!confirmed) return;
    try {
      await runMutationWithContext(async () => {
        const call = await withScopedApiRequestHeaders(
          buildOptimisticLockHeader(user.updatedAt),
          () => apiCall(
            `/api/customer_accounts/admin/users/${encodeURIComponent(user.id)}`,
            {
              method: "PUT",
              headers: { "content-type": "application/json" },
              body: JSON.stringify({ isActive: nextActive })
            }
          )
        );
        if (!call.ok) {
          flash(t("customer_accounts.admin.error.toggleActive", "Failed to update user status"), "error");
          return;
        }
        flash(
          nextActive ? t("customer_accounts.admin.flash.activated", "User activated") : t("customer_accounts.admin.flash.deactivated", "User deactivated"),
          "success"
        );
        setReloadToken((token) => token + 1);
      }, { userId: user.id, isActive: nextActive });
    } catch (err) {
      const message = err instanceof Error ? err.message : t("customer_accounts.admin.error.toggleActive", "Failed to update user status");
      flash(message, "error");
    }
  }, [confirm, runMutationWithContext, t]);
  const handleDelete = React.useCallback(async (user) => {
    const confirmed = await confirm({
      title: t("customer_accounts.admin.confirm.delete", 'Delete user "{{name}}"?', {
        name: user.displayName || user.email
      }),
      variant: "destructive"
    });
    if (!confirmed) return;
    try {
      await runMutationWithContext(async () => {
        const call = await withScopedApiRequestHeaders(
          buildOptimisticLockHeader(user.updatedAt),
          () => apiCall(
            `/api/customer_accounts/admin/users/${encodeURIComponent(user.id)}`,
            { method: "DELETE" }
          )
        );
        if (!call.ok) {
          flash(t("customer_accounts.admin.error.delete", "Failed to delete user"), "error");
          return;
        }
        flash(t("customer_accounts.admin.flash.deleted", "User deleted"), "success");
        setReloadToken((token) => token + 1);
      }, { id: user.id });
    } catch (err) {
      const message = err instanceof Error ? err.message : t("customer_accounts.admin.error.delete", "Failed to delete user");
      flash(message, "error");
    }
  }, [confirm, runMutationWithContext, t]);
  const handleFiltersApply = React.useCallback((values) => {
    setFilterValues(values);
    setPage(1);
  }, []);
  const handleFiltersClear = React.useCallback(() => {
    setFilterValues({});
    setPage(1);
  }, []);
  const columns = React.useMemo(() => {
    const noValue = /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-sm", children: "-" });
    return [
      {
        accessorKey: "displayName",
        header: t("customer_accounts.admin.columns.displayName", "Name"),
        cell: ({ row }) => /* @__PURE__ */ jsx(
          Link,
          {
            href: `/backend/customer_accounts/users/${row.original.id}`,
            className: "font-medium hover:underline",
            children: row.original.displayName || row.original.email
          }
        )
      },
      {
        accessorKey: "email",
        header: t("customer_accounts.admin.columns.email", "Email")
      },
      {
        accessorKey: "emailVerified",
        header: t("customer_accounts.admin.columns.emailVerified", "Verified"),
        cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: `inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${row.original.emailVerified ? "bg-status-success-bg text-status-success-text" : "bg-status-warning-bg text-status-warning-text"}`, children: row.original.emailVerified ? t("customer_accounts.admin.verified", "Yes") : t("customer_accounts.admin.unverified", "No") })
      },
      {
        accessorKey: "isActive",
        header: t("customer_accounts.admin.columns.status", "Status"),
        cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: `inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${row.original.isActive ? "bg-status-success-bg text-status-success-text" : "bg-status-error-bg text-status-error-text"}`, children: row.original.isActive ? t("customer_accounts.admin.active", "Active") : t("customer_accounts.admin.inactive", "Inactive") })
      },
      {
        accessorKey: "lastLoginAt",
        header: t("customer_accounts.admin.columns.lastLogin", "Last Login"),
        cell: ({ row }) => formatDate(row.original.lastLoginAt, "-") || noValue
      },
      {
        accessorKey: "roles",
        header: t("customer_accounts.admin.columns.roles", "Roles"),
        cell: ({ row }) => {
          const roles = row.original.roles;
          if (!roles || !roles.length) return noValue;
          return /* @__PURE__ */ jsx("span", { className: "text-sm", children: roles.map((r) => r.name).join(", ") });
        }
      },
      {
        accessorKey: "createdAt",
        header: t("customer_accounts.admin.columns.createdAt", "Created"),
        cell: ({ row }) => formatDate(row.original.createdAt, "-")
      }
    ];
  }, [t]);
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsxs(PageBody, { className: "space-y-4", children: [
      /* @__PURE__ */ jsx("div", { className: "rounded-lg border border-status-info-border bg-status-info-bg p-4", children: /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-4", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("h3", { className: "text-sm font-medium text-status-info-text", children: t("customer_accounts.admin.portalInfo.title", "Customer Portal") }),
          /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-status-info-text", children: t("customer_accounts.admin.portalInfo.description", "Manage customer portal accounts. Customers can self-register, log in, and access orders, quotes, and invoices through the portal.") }),
          /* @__PURE__ */ jsx("p", { className: "mt-1.5 text-xs text-status-info-text", children: t("customer_accounts.admin.portalInfo.url", "Portal URL: {url}", {
            url: `${typeof window !== "undefined" ? window.location.origin : ""}/[org-slug]/portal`
          }) }),
          /* @__PURE__ */ jsx("p", { className: "mt-0.5 text-xs text-status-info-text", children: t("customer_accounts.admin.portalInfo.credentials", "Demo credentials: alice.johnson@example.com / Password123!") })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 flex-col gap-2", children: [
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              variant: "outline",
              size: "sm",
              asChild: true,
              children: /* @__PURE__ */ jsxs(Link, { href: "/backend/customer_accounts/settings", children: [
                /* @__PURE__ */ jsx(Settings, { className: "size-4" }),
                t("customer_accounts.admin.portalInfo.openConfiguration", "Open Configuration")
              ] })
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              variant: "outline",
              size: "sm",
              asChild: true,
              children: /* @__PURE__ */ jsxs("a", { href: `${typeof window !== "undefined" ? window.location.origin : ""}/portal`, target: "_blank", rel: "noopener noreferrer", children: [
                /* @__PURE__ */ jsx(Globe, { className: "size-4" }),
                t("customer_accounts.admin.portalInfo.open", "Open Portal")
              ] })
            }
          )
        ] })
      ] }) }),
      /* @__PURE__ */ jsx(
        DataTable,
        {
          stickyActionsColumn: true,
          title: t("customer_accounts.admin.title", "Users"),
          actions: /* @__PURE__ */ jsx(Button, { onClick: () => setCreateDialogOpen(true), children: t("customer_accounts.admin.actions.createUser", "Create User") }),
          columns,
          data: rows,
          searchValue: search,
          onSearchChange: (value) => {
            setSearch(value);
            setPage(1);
          },
          searchPlaceholder: t("customer_accounts.admin.searchPlaceholder", "Search by name or email..."),
          filters,
          filterValues,
          onFiltersApply: handleFiltersApply,
          onFiltersClear: handleFiltersClear,
          perspective: { tableId: "customer_accounts.admin.users" },
          emptyState: /* @__PURE__ */ jsx(
            ListEmptyState,
            {
              entityName: t("customer_accounts.admin.title", "Users"),
              onCreate: () => setCreateDialogOpen(true),
              createLabel: t("customer_accounts.admin.actions.createUser", "Create User")
            }
          ),
          onRowClick: (row) => router.push(`/backend/customer_accounts/users/${row.id}`),
          rowActions: (row) => /* @__PURE__ */ jsx(
            RowActions,
            {
              items: [
                {
                  id: "view",
                  label: t("customer_accounts.admin.actions.view", "View"),
                  onSelect: () => {
                    router.push(`/backend/customer_accounts/users/${row.id}`);
                  }
                },
                {
                  id: "toggle-active",
                  label: row.isActive ? t("customer_accounts.admin.actions.deactivate", "Deactivate") : t("customer_accounts.admin.actions.activate", "Activate"),
                  onSelect: () => {
                    void handleToggleActive(row);
                  }
                },
                {
                  id: "delete",
                  label: t("customer_accounts.admin.actions.delete", "Delete"),
                  destructive: true,
                  onSelect: () => {
                    void handleDelete(row);
                  }
                }
              ]
            }
          ),
          pagination: { page, pageSize, total, totalPages, onPageChange: setPage },
          isLoading
        }
      ),
      /* @__PURE__ */ jsx(
        CreateUserDialog,
        {
          open: createDialogOpen,
          onOpenChange: setCreateDialogOpen,
          roleOptions,
          onCreated: () => setReloadToken((token) => token + 1),
          onRunMutation: runMutationWithContext
        }
      )
    ] }),
    ConfirmDialogElement
  ] });
}
export {
  CustomerAccountsPage as default
};
//# sourceMappingURL=page.js.map
