"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Mail, Phone, X } from "lucide-react";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { apiCallOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { LookupSelect } from "@open-mercato/ui/backend/inputs/LookupSelect";
import { IconButton } from "@open-mercato/ui/primitives/icon-button";
import { Avatar } from "@open-mercato/ui/primitives/avatar";
import { Button } from "@open-mercato/ui/primitives/button";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { fetchAssignableStaffMembers } from "./assignableStaff.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customers");
function formatAssignedAt(value, t) {
  if (!value) return null;
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return null;
  const diffMs = Date.now() - date.getTime();
  const diffDays = Math.floor(diffMs / 864e5);
  if (diffDays <= 0) return t("customers.roles.assignedToday", "Assigned today");
  if (diffDays === 1) return t("customers.roles.assignedYesterday", "Assigned yesterday");
  return t("customers.roles.assignedDaysAgo", "Assigned {{count}} days ago", { count: diffDays });
}
function RoleAssignmentRow({
  role,
  roleTypeLabel,
  runMutationWithContext,
  entityType,
  entityId,
  onRemoved,
  onUpdated
}) {
  const t = useT();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const [removing, setRemoving] = React.useState(false);
  const [changingUser, setChangingUser] = React.useState(false);
  const searchUsers = React.useCallback(async (query) => {
    try {
      const members = await fetchAssignableStaffMembers(query, { pageSize: 20 });
      return members.map((member) => ({
        id: member.userId,
        title: member.displayName,
        subtitle: member.displayName && member.email ? member.email : null
      }));
    } catch (error) {
      logger.error("customers.roles.searchUsers failed", { err: error });
      return [];
    }
  }, []);
  const handleUserChange = React.useCallback(async (userId) => {
    if (!userId || userId === role.userId) return;
    const basePath = entityType === "company" ? "companies" : "people";
    try {
      await runMutationWithContext(
        () => (
          // optimistic-lock-exempt: role assignment add/remove
          apiCallOrThrow(`/api/customers/${basePath}/${entityId}/roles?roleId=${role.id}`, {
            method: "PUT",
            headers: { "content-type": "application/json" },
            body: JSON.stringify({ userId })
          })
        ),
        { roleId: role.id, userId }
      );
      setChangingUser(false);
      onUpdated();
    } catch (error) {
      logger.error("customers.roles.update failed", { err: error });
      flash(t("customers.roles.updateFailed", "Failed to update role assignment."), "error");
      setChangingUser(false);
    }
  }, [entityId, entityType, onUpdated, role.id, role.userId, runMutationWithContext, t]);
  const handleRemove = React.useCallback(async () => {
    const confirmed = await confirm({
      title: t("customers.roles.removeConfirm", "Remove this role assignment?"),
      variant: "default"
    });
    if (!confirmed) return;
    setRemoving(true);
    const basePath = entityType === "company" ? "companies" : "people";
    try {
      await runMutationWithContext(
        () => (
          // optimistic-lock-exempt: role assignment add/remove
          apiCallOrThrow(`/api/customers/${basePath}/${entityId}/roles?roleId=${role.id}`, {
            method: "DELETE"
          })
        ),
        { roleId: role.id }
      );
      onRemoved();
    } catch (error) {
      logger.error("customers.roles.remove failed", { err: error });
      flash(t("customers.roles.removeFailed", "Failed to remove role assignment."), "error");
    } finally {
      setRemoving(false);
    }
  }, [confirm, entityId, entityType, onRemoved, role.id, runMutationWithContext, t]);
  const currentUserOptions = React.useMemo(
    () => role.userId ? [{
      id: role.userId,
      title: role.userName ?? role.userEmail ?? role.userId,
      subtitle: role.userName && role.userEmail ? role.userEmail : null
    }] : [],
    [role.userEmail, role.userId, role.userName]
  );
  const userLabel = React.useMemo(() => {
    return role.userName ?? role.userEmail ?? "?";
  }, [role.userEmail, role.userName]);
  const displayName = role.userName ?? role.userEmail ?? role.userId;
  const assignedLabel = formatAssignedAt(role.createdAt, t);
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    ConfirmDialogElement,
    /* @__PURE__ */ jsxs("div", { className: "flex h-full min-w-0 flex-col overflow-hidden rounded-xl border bg-card p-4 shadow-sm", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-start justify-between gap-3", children: [
        /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "max-w-full break-words rounded-full px-2 py-0 text-left text-xs font-semibold", children: roleTypeLabel }),
        /* @__PURE__ */ jsx(
          IconButton,
          {
            type: "button",
            variant: "ghost",
            size: "sm",
            onClick: handleRemove,
            disabled: removing,
            "aria-label": t("customers.roles.remove", "Remove role"),
            children: /* @__PURE__ */ jsx(X, { className: "size-4" })
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "mt-4 flex min-w-0 flex-col gap-3 sm:flex-row sm:items-start", children: [
        /* @__PURE__ */ jsx(Avatar, { label: userLabel, size: "lg", variant: "monochrome" }),
        /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
          /* @__PURE__ */ jsx("div", { className: "break-all text-sm font-semibold leading-5 text-foreground", children: displayName }),
          role.userEmail ? /* @__PURE__ */ jsx("div", { className: "mt-1 break-all text-xs text-muted-foreground", children: role.userEmail }) : null,
          assignedLabel ? /* @__PURE__ */ jsx("div", { className: "mt-2 text-overline uppercase tracking-[0.08em] text-muted-foreground", children: assignedLabel }) : null
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "mt-4 flex flex-wrap items-center gap-2", children: [
        role.userEmail ? /* @__PURE__ */ jsx(IconButton, { asChild: true, variant: "outline", size: "sm", className: "shrink-0", children: /* @__PURE__ */ jsx("a", { href: `mailto:${role.userEmail}`, "aria-label": t("customers.roles.email", "Send email"), children: /* @__PURE__ */ jsx(Mail, { className: "size-4" }) }) }) : /* @__PURE__ */ jsx(
          IconButton,
          {
            type: "button",
            variant: "outline",
            size: "sm",
            className: "shrink-0",
            disabled: true,
            "aria-label": t("customers.roles.emailUnavailable", "Email unavailable"),
            children: /* @__PURE__ */ jsx(Mail, { className: "size-4" })
          }
        ),
        role.userPhone ? /* @__PURE__ */ jsx(IconButton, { asChild: true, variant: "outline", size: "sm", className: "shrink-0", children: /* @__PURE__ */ jsx("a", { href: `tel:${role.userPhone}`, "aria-label": t("customers.roles.call", "Call"), children: /* @__PURE__ */ jsx(Phone, { className: "size-4" }) }) }) : /* @__PURE__ */ jsx(
          IconButton,
          {
            type: "button",
            variant: "outline",
            size: "sm",
            className: "shrink-0",
            disabled: true,
            "aria-label": t("customers.roles.phoneUnavailable", "Phone unavailable"),
            children: /* @__PURE__ */ jsx(Phone, { className: "size-4" })
          }
        ),
        /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            variant: "ghost",
            size: "sm",
            className: "h-auto w-full justify-start px-2 py-1 text-xs sm:ml-auto sm:w-auto",
            onClick: () => setChangingUser((current) => !current),
            children: t("customers.roles.changeUser", "Change user")
          }
        )
      ] }),
      changingUser ? /* @__PURE__ */ jsx("div", { className: "mt-4 border-t pt-4", children: /* @__PURE__ */ jsx(
        LookupSelect,
        {
          value: role.userId,
          onChange: async (userId) => {
            await handleUserChange(userId);
          },
          fetchItems: searchUsers,
          options: currentUserOptions,
          placeholder: t("customers.roles.searchPlaceholder", "Search team member...")
        }
      ) }) : null
    ] })
  ] });
}
export {
  RoleAssignmentRow
};
//# sourceMappingURL=RoleAssignmentRow.js.map
