"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { Search, Check, CheckCheck, Settings2 } from "lucide-react";
import { Avatar } from "@open-mercato/ui/primitives/avatar";
import { EmptyState } from "@open-mercato/ui/primitives/empty-state";
import { StepIndicator } from "@open-mercato/ui/primitives/step-indicator";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Button } from "@open-mercato/ui/primitives/button";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { Input } from "@open-mercato/ui/primitives/input";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { fetchAssignableStaffMembersPage } from "./assignableStaff.js";
const MANAGE_ROLE_TYPES_HREF = "/backend/config/customers";
const ASSIGNABLE_STAFF_PAGE_SIZE = 24;
function AssignRoleDialog({
  open,
  onClose,
  onAssign,
  roleTypes,
  entityName,
  existingRoleTypes,
  existingAssignments = [],
  initialRoleType = null,
  canManageRoleTypes = false
}) {
  const t = useT();
  const [step, setStep] = React.useState(1);
  const [selectedRoleType, setSelectedRoleType] = React.useState("");
  const [selectedUser, setSelectedUser] = React.useState(null);
  const [searchQuery, setSearchQuery] = React.useState("");
  const [users, setUsers] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [loadingMore, setLoadingMore] = React.useState(false);
  const [saving, setSaving] = React.useState(false);
  const [activeTeam, setActiveTeam] = React.useState("all");
  const [loadError, setLoadError] = React.useState(null);
  const [totalUsers, setTotalUsers] = React.useState(0);
  const [currentPage, setCurrentPage] = React.useState(1);
  const deferredSearchQuery = React.useDeferredValue(searchQuery);
  const requestSequenceRef = React.useRef(0);
  const availableRoleTypes = React.useMemo(
    () => roleTypes.filter((roleType) => !existingRoleTypes?.has(roleType.value)),
    [existingRoleTypes, roleTypes]
  );
  React.useEffect(() => {
    if (!open) {
      setStep(1);
      setSelectedRoleType("");
      setSelectedUser(null);
      setSearchQuery("");
      setUsers([]);
      setActiveTeam("all");
      setLoadError(null);
      setTotalUsers(0);
      setCurrentPage(1);
      requestSequenceRef.current = 0;
      return;
    }
    const resolvedInitialRoleType = typeof initialRoleType === "string" && initialRoleType.trim().length > 0 ? initialRoleType.trim() : "";
    setStep(resolvedInitialRoleType ? 2 : 1);
    setSelectedRoleType(resolvedInitialRoleType);
    setSelectedUser(null);
    setSearchQuery("");
    setUsers([]);
    setActiveTeam("all");
    setLoadError(null);
    setTotalUsers(0);
    setCurrentPage(1);
    requestSequenceRef.current = 0;
  }, [initialRoleType, open]);
  const searchUsers = React.useCallback(
    async ({
      query,
      page,
      append
    }) => {
      const requestId = append ? requestSequenceRef.current : requestSequenceRef.current + 1;
      requestSequenceRef.current = requestId;
      if (append) {
        setLoadingMore(true);
      } else {
        setLoading(true);
      }
      try {
        const result = await fetchAssignableStaffMembersPage(query, {
          page,
          pageSize: ASSIGNABLE_STAFF_PAGE_SIZE
        });
        if (requestSequenceRef.current !== requestId) return;
        const nextUsers = result.items.map((member) => ({
          id: member.userId,
          displayName: member.displayName,
          email: member.email,
          teamName: member.teamName
        }));
        setUsers((current) => {
          if (!append) return nextUsers;
          const merged = new Map(current.map((user) => [user.id, user]));
          nextUsers.forEach((user) => merged.set(user.id, user));
          return Array.from(merged.values());
        });
        setTotalUsers(result.total);
        setCurrentPage(result.page);
        setLoadError(null);
      } catch {
        if (requestSequenceRef.current !== requestId) return;
        if (!append) {
          setUsers([]);
          setTotalUsers(0);
          setCurrentPage(1);
        }
        setLoadError(
          t(
            "customers.assignableStaff.loadError",
            "Unable to load team members. Check your permissions and try again."
          )
        );
      } finally {
        if (requestSequenceRef.current !== requestId) return;
        if (append) {
          setLoadingMore(false);
        } else {
          setLoading(false);
        }
      }
    },
    [t]
  );
  React.useEffect(() => {
    if (step >= 2) {
      searchUsers({ query: deferredSearchQuery, page: 1, append: false }).catch(() => {
      });
    }
  }, [deferredSearchQuery, searchUsers, step]);
  const handleLoadMore = React.useCallback(() => {
    if (loading || loadingMore || users.length >= totalUsers) return;
    searchUsers({
      query: deferredSearchQuery,
      page: currentPage + 1,
      append: true
    }).catch(() => {
    });
  }, [currentPage, deferredSearchQuery, loading, loadingMore, searchUsers, totalUsers, users.length]);
  const selectedRole = React.useMemo(
    () => roleTypes.find((roleType) => roleType.value === selectedRoleType) ?? null,
    [roleTypes, selectedRoleType]
  );
  const roleTypeLabelMap = React.useMemo(
    () => new Map(roleTypes.map((roleType) => [roleType.value, roleType.label])),
    [roleTypes]
  );
  const conflictsByUserId = React.useMemo(() => {
    const next = /* @__PURE__ */ new Map();
    existingAssignments.forEach((assignment) => {
      if (!assignment.userId) return;
      if (assignment.roleType === selectedRoleType) return;
      const label = roleTypeLabelMap.get(assignment.roleType) ?? assignment.roleType;
      const current = next.get(assignment.userId) ?? [];
      if (!current.includes(label)) {
        current.push(label);
        next.set(assignment.userId, current);
      }
    });
    return next;
  }, [existingAssignments, roleTypeLabelMap, selectedRoleType]);
  const selectedUserConflict = React.useMemo(() => {
    if (!selectedUser) return null;
    return conflictsByUserId.get(selectedUser.id) ?? null;
  }, [conflictsByUserId, selectedUser]);
  const teamFilters = React.useMemo(() => {
    const counts = /* @__PURE__ */ new Map();
    users.forEach((user) => {
      const key = user.teamName?.trim() || t("customers.roles.dialog.team.unassigned", "No team");
      counts.set(key, (counts.get(key) ?? 0) + 1);
    });
    return [
      { id: "all", label: t("customers.roles.dialog.team.all", "All"), count: users.length },
      ...Array.from(counts.entries()).map(([label, count]) => ({ id: label, label, count }))
    ];
  }, [t, users]);
  const filteredUsers = React.useMemo(() => {
    if (activeTeam === "all") return users;
    return users.filter(
      (user) => (user.teamName?.trim() || t("customers.roles.dialog.team.unassigned", "No team")) === activeTeam
    );
  }, [activeTeam, t, users]);
  const visibleCountLabel = React.useMemo(() => {
    if (totalUsers <= 0) return null;
    return t(
      "customers.roles.dialog.visibleCount",
      "Showing {{shown}} of {{total}} team members",
      {
        shown: String(users.length),
        total: String(totalUsers)
      }
    );
  }, [t, totalUsers, users.length]);
  const canLoadMore = users.length < totalUsers;
  const handleAssign = React.useCallback(async () => {
    if (!selectedRoleType || !selectedUser) return;
    setSaving(true);
    try {
      await onAssign(selectedRoleType, selectedUser.id);
      onClose();
    } finally {
      setSaving(false);
    }
  }, [onAssign, onClose, selectedRoleType, selectedUser]);
  const handleKeyDown = React.useCallback(
    (e) => {
      if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
        e.preventDefault();
        if (step === 3 && !saving && selectedUser && selectedRoleType) {
          handleAssign();
        } else if (step === 1 && selectedRoleType && availableRoleTypes.length) {
          setStep(2);
        } else if (step === 2 && selectedUser) {
          setStep(3);
        }
      }
    },
    [availableRoleTypes.length, handleAssign, saving, selectedRoleType, selectedUser, step]
  );
  const previewCard = selectedUser && selectedRole ? /* @__PURE__ */ jsxs("div", { className: "rounded-lg border border-border/70 bg-muted/30 px-4 py-4", children: [
    /* @__PURE__ */ jsx("p", { className: "text-overline font-semibold uppercase tracking-[0.12em] text-muted-foreground", children: t("customers.roles.dialog.preview", "Assignment preview") }),
    /* @__PURE__ */ jsxs("div", { className: "mt-3 flex items-center gap-3", children: [
      /* @__PURE__ */ jsx(
        Avatar,
        {
          label: selectedUser.displayName,
          size: "lg",
          className: "bg-background text-foreground"
        }
      ),
      /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2 text-sm font-semibold text-foreground", children: [
          /* @__PURE__ */ jsx("span", { children: selectedUser.displayName }),
          /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "\u2192" }),
          /* @__PURE__ */ jsx("span", { children: selectedRole.label })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "mt-1 flex flex-wrap items-center gap-3 text-xs text-muted-foreground", children: [
          selectedUser.email ? /* @__PURE__ */ jsx("span", { children: selectedUser.email }) : null,
          selectedUser.teamName ? /* @__PURE__ */ jsx("span", { children: selectedUser.teamName }) : null
        ] }),
        selectedUserConflict?.length ? /* @__PURE__ */ jsx("div", { className: "mt-2 flex flex-wrap items-center gap-2", children: /* @__PURE__ */ jsx(
          Badge,
          {
            variant: "outline",
            className: "rounded-full border-status-error-border bg-status-error-bg px-2 py-0.5 text-xs font-semibold text-status-error-text",
            children: t("customers.roles.dialog.conflict", "Conflict: {{roles}}", {
              roles: selectedUserConflict.join(", ")
            })
          }
        ) }) : null
      ] })
    ] })
  ] }) : null;
  return /* @__PURE__ */ jsx(
    Dialog,
    {
      open,
      onOpenChange: (nextOpen) => {
        if (!nextOpen) onClose();
      },
      children: /* @__PURE__ */ jsxs(
        DialogContent,
        {
          className: "min-h-0 max-h-[min(90vh,760px)] overflow-hidden p-0 sm:max-w-[580px]",
          onKeyDown: handleKeyDown,
          children: [
            /* @__PURE__ */ jsxs(DialogHeader, { className: "border-b border-border/70 px-6 py-5", children: [
              /* @__PURE__ */ jsx(DialogTitle, { className: "text-2xl font-semibold leading-none", children: t("customers.roles.dialog.title", "Assign role") }),
              /* @__PURE__ */ jsx("p", { className: "mt-2 text-sm text-muted-foreground", children: t("customers.roles.dialog.subtitle", "Multi-role assignment for {{name}}", {
                name: entityName
              }) })
            ] }),
            /* @__PURE__ */ jsx("div", { className: "border-b border-border/70 px-6 py-4", children: /* @__PURE__ */ jsx(
              StepIndicator,
              {
                className: "justify-center",
                steps: [
                  {
                    id: "1",
                    label: t("customers.roles.dialog.step1", "Role type"),
                    status: step > 1 ? "complete" : step === 1 ? "current" : "pending"
                  },
                  {
                    id: "2",
                    label: t("customers.roles.dialog.step2", "Select person"),
                    status: step > 2 ? "complete" : step === 2 ? "current" : "pending"
                  },
                  {
                    id: "3",
                    label: t("customers.roles.dialog.step3", "Confirm"),
                    status: step === 3 ? "current" : "pending"
                  }
                ]
              }
            ) }),
            /* @__PURE__ */ jsx("div", { className: "min-h-0 flex-1 overflow-y-auto", children: /* @__PURE__ */ jsxs("div", { className: "space-y-5 px-6 py-5", children: [
              step === 1 ? /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
                /* @__PURE__ */ jsxs("div", { className: "rounded-lg bg-muted/30 px-4 py-4", children: [
                  /* @__PURE__ */ jsx(
                    "p",
                    {
                      id: "assign-role-dialog-type-label",
                      className: "text-overline font-semibold uppercase tracking-[0.12em] text-muted-foreground",
                      children: t("customers.roles.dialog.roleTypeLabel", "Role type")
                    }
                  ),
                  /* @__PURE__ */ jsxs("div", { className: "mt-2 flex items-center gap-2", children: [
                    /* @__PURE__ */ jsxs(
                      "select",
                      {
                        "aria-labelledby": "assign-role-dialog-type-label",
                        value: selectedRoleType,
                        onChange: (event) => setSelectedRoleType(event.target.value),
                        className: "h-10 w-full rounded-md border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-ring/30",
                        children: [
                          /* @__PURE__ */ jsx("option", { value: "", children: t("customers.roles.selectRoleType", "Select role type...") }),
                          availableRoleTypes.map((roleType) => /* @__PURE__ */ jsx("option", { value: roleType.value, children: roleType.label }, roleType.id))
                        ]
                      }
                    ),
                    selectedRole ? /* @__PURE__ */ jsx(
                      Badge,
                      {
                        variant: "outline",
                        className: "rounded-md px-2 py-1 text-xs",
                        children: t("customers.roles.dialog.sourceBadge.dictionary", "Dictionary")
                      }
                    ) : null
                  ] }),
                  canManageRoleTypes ? /* @__PURE__ */ jsxs(
                    Link,
                    {
                      href: MANAGE_ROLE_TYPES_HREF,
                      className: "mt-3 inline-flex items-center gap-1.5 text-xs font-medium text-primary hover:underline",
                      "data-testid": "assign-role-dialog-manage-role-types",
                      children: [
                        /* @__PURE__ */ jsx(Settings2, { className: "size-3.5", "aria-hidden": "true" }),
                        t("customers.roles.dialog.manageRoleTypes", "Manage role types")
                      ]
                    }
                  ) : null
                ] }),
                !availableRoleTypes.length ? /* @__PURE__ */ jsx(
                  EmptyState,
                  {
                    size: "sm",
                    icon: /* @__PURE__ */ jsx(CheckCheck, { className: "h-8 w-8", "aria-hidden": "true" }),
                    title: t(
                      "customers.roles.dialog.noAvailableRoles",
                      "All available role types are already assigned."
                    )
                  }
                ) : null
              ] }) : null,
              step === 2 ? /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
                /* @__PURE__ */ jsx("div", { className: "rounded-lg bg-muted/30 px-4 py-4", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
                  /* @__PURE__ */ jsxs("div", { children: [
                    /* @__PURE__ */ jsx("p", { className: "text-overline font-semibold uppercase tracking-[0.12em] text-muted-foreground", children: t("customers.roles.dialog.roleTypeLabel", "Role type") }),
                    /* @__PURE__ */ jsxs("div", { className: "mt-1 flex items-center gap-2", children: [
                      /* @__PURE__ */ jsx("span", { className: "text-lg font-semibold text-foreground", children: selectedRole?.label ?? selectedRoleType }),
                      /* @__PURE__ */ jsx(
                        Badge,
                        {
                          variant: "outline",
                          className: "rounded-md px-2 py-1 text-xs",
                          children: t("customers.roles.dialog.sourceBadge.dictionary", "Dictionary")
                        }
                      )
                    ] })
                  ] }),
                  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                    canManageRoleTypes ? /* @__PURE__ */ jsx(Button, { asChild: true, variant: "ghost", size: "sm", children: /* @__PURE__ */ jsxs(
                      Link,
                      {
                        href: MANAGE_ROLE_TYPES_HREF,
                        "data-testid": "assign-role-dialog-manage-role-types-step2",
                        children: [
                          /* @__PURE__ */ jsx(Settings2, { className: "mr-1 size-3.5", "aria-hidden": "true" }),
                          t("customers.roles.dialog.manageRoleTypes", "Manage role types")
                        ]
                      }
                    ) }) : null,
                    /* @__PURE__ */ jsx(
                      Button,
                      {
                        type: "button",
                        variant: "outline",
                        size: "sm",
                        onClick: () => setStep(1),
                        children: t("customers.roles.dialog.change", "Change")
                      }
                    )
                  ] })
                ] }) }),
                /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                  /* @__PURE__ */ jsx("p", { className: "text-overline font-semibold uppercase tracking-[0.12em] text-muted-foreground", children: t("customers.roles.dialog.teamLabel", "Select a team member") }),
                  /* @__PURE__ */ jsxs("div", { className: "relative", children: [
                    /* @__PURE__ */ jsx(Search, { className: "absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" }),
                    /* @__PURE__ */ jsx(
                      Input,
                      {
                        value: searchQuery,
                        onChange: (event) => setSearchQuery(event.target.value),
                        placeholder: t(
                          "customers.roles.dialog.searchPlaceholder",
                          "Search by name, e-mail or team..."
                        ),
                        className: "h-10 rounded-md border-border/80 pl-9 shadow-none"
                      }
                    )
                  ] })
                ] }),
                /* @__PURE__ */ jsx("div", { className: "flex flex-wrap items-center gap-2", children: teamFilters.map((teamFilter) => {
                  const isActive = activeTeam === teamFilter.id;
                  return /* @__PURE__ */ jsxs(
                    Button,
                    {
                      type: "button",
                      variant: isActive ? "default" : "outline",
                      size: "sm",
                      onClick: () => setActiveTeam(teamFilter.id),
                      className: "h-7 rounded-md px-2.5 text-xs",
                      children: [
                        teamFilter.label,
                        /* @__PURE__ */ jsx("span", { className: "rounded-full bg-background/80 px-1 text-xs text-muted-foreground", children: teamFilter.count })
                      ]
                    },
                    teamFilter.id
                  );
                }) }),
                /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                  visibleCountLabel ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: visibleCountLabel }) : null,
                  loading ? /* @__PURE__ */ jsx("div", { className: "rounded-lg border border-dashed border-border/80 px-4 py-8 text-center text-sm text-muted-foreground", children: t("customers.roles.loading", "Loading...") }) : loadError ? /* @__PURE__ */ jsx("div", { className: "rounded-lg border border-dashed border-status-error-border bg-status-error-bg/70 px-4 py-8 text-center text-sm text-status-error-text", children: loadError }) : filteredUsers.length === 0 ? /* @__PURE__ */ jsx("div", { className: "rounded-lg border border-dashed border-border/80 px-4 py-8 text-center text-sm text-muted-foreground", children: t(
                    "customers.roles.dialog.noResults",
                    "No matching team members found."
                  ) }) : filteredUsers.map((user) => {
                    const isSelected = selectedUser?.id === user.id;
                    const userConflicts = conflictsByUserId.get(user.id) ?? [];
                    return /* @__PURE__ */ jsxs(
                      Button,
                      {
                        type: "button",
                        variant: "ghost",
                        onClick: () => setSelectedUser(user),
                        className: `h-auto flex w-full items-center gap-3 rounded-lg border px-4 py-3 text-left transition-colors ${isSelected ? "border-foreground bg-background shadow-sm" : "border-border/70 bg-background hover:bg-accent/40"}`,
                        children: [
                          /* @__PURE__ */ jsx(Avatar, { label: user.displayName, size: "lg", variant: "monochrome" }),
                          /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
                            /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
                              /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold text-foreground", children: user.displayName }),
                              user.teamName ? /* @__PURE__ */ jsx(
                                Badge,
                                {
                                  variant: "muted",
                                  className: "rounded-md px-2 py-0.5 text-xs font-medium",
                                  children: user.teamName
                                }
                              ) : null,
                              userConflicts.length ? /* @__PURE__ */ jsx(
                                Badge,
                                {
                                  variant: "outline",
                                  className: "rounded-full border-status-error-border bg-status-error-bg px-2 py-0.5 text-xs font-semibold text-status-error-text",
                                  children: t("customers.roles.dialog.conflict", "Conflict: {{roles}}", {
                                    roles: userConflicts.join(", ")
                                  })
                                }
                              ) : null
                            ] }),
                            user.email ? /* @__PURE__ */ jsx("div", { className: "mt-1 text-xs text-muted-foreground", children: user.email }) : null
                          ] }),
                          /* @__PURE__ */ jsx(
                            "span",
                            {
                              className: `flex size-6 shrink-0 items-center justify-center rounded-full border ${isSelected ? "border-foreground bg-foreground text-background" : "border-border/80 bg-background text-transparent"}`,
                              children: /* @__PURE__ */ jsx(Check, { className: "size-3.5" })
                            }
                          )
                        ]
                      },
                      user.id
                    );
                  }),
                  canLoadMore && !loadError ? /* @__PURE__ */ jsx(
                    Button,
                    {
                      type: "button",
                      variant: "outline",
                      onClick: handleLoadMore,
                      disabled: loadingMore,
                      className: "w-full",
                      children: loadingMore ? t("customers.roles.dialog.loadingMore", "Loading more...") : t("customers.roles.dialog.loadMore", "Load more")
                    }
                  ) : null
                ] }),
                previewCard
              ] }) : null,
              step === 3 ? /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
                previewCard,
                /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t(
                  "customers.roles.dialog.constraint",
                  "One person per role. The assignment can be changed at any time."
                ) })
              ] }) : null
            ] }) }),
            /* @__PURE__ */ jsxs(DialogFooter, { className: "shrink-0 border-t border-border/70 px-6 py-4 sm:justify-between", children: [
              /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
                "customers.roles.dialog.footerNote",
                "One person per role \xB7 can be changed at any time"
              ) }),
              /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: onClose, children: t("customers.roles.cancelAdd", "Cancel") }),
                step === 1 ? /* @__PURE__ */ jsx(
                  Button,
                  {
                    type: "button",
                    onClick: () => setStep(2),
                    disabled: !selectedRoleType || !availableRoleTypes.length,
                    children: t("customers.roles.dialog.next", "Next")
                  }
                ) : null,
                step === 2 ? /* @__PURE__ */ jsx(Button, { type: "button", onClick: () => setStep(3), disabled: !selectedUser, children: t("customers.roles.dialog.next", "Next") }) : null,
                step === 3 ? /* @__PURE__ */ jsx(
                  Button,
                  {
                    type: "button",
                    onClick: handleAssign,
                    disabled: saving || !selectedUser || !selectedRoleType,
                    children: saving ? t("customers.roles.assigning", "Assigning...") : t("customers.roles.dialog.assign", "Assign role")
                  }
                ) : null
              ] })
            ] })
          ]
        }
      )
    }
  );
}
export {
  AssignRoleDialog
};
//# sourceMappingURL=AssignRoleDialog.js.map
