"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { ErrorMessage, RecordNotFoundState } from "@open-mercato/ui/backend/detail";
import { readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { updateCrud, deleteCrud } from "@open-mercato/ui/backend/utils/crud";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { DataTable, withDataTableNamespaces } from "@open-mercato/ui/backend/DataTable";
import { RowActions } from "@open-mercato/ui/backend/RowActions";
import { Button } from "@open-mercato/ui/primitives/button";
import { BooleanIcon } from "@open-mercato/ui/backend/ValueIcons";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { TeamForm, buildTeamPayload } from "@open-mercato/core/modules/staff/components/TeamForm";
import { buildRecordInjectionContext, useSetCurrentRecordInjectionContext } from "@open-mercato/ui/backend/injection/recordContext";
import { SendObjectMessageDialog } from "@open-mercato/ui/backend/messages";
import { extractCustomFieldEntries } from "@open-mercato/shared/lib/crud/custom-fields-client";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { Plus } from "lucide-react";
import { formatDateTime } from "@open-mercato/shared/lib/time";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("staff");
const TEAM_MEMBERS_PAGE_SIZE = 50;
function StaffTeamEditPage({ params }) {
  const teamId = params?.id;
  const t = useT();
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const scopeVersion = useOrganizationScopeVersion();
  const [initialValues, setInitialValues] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [isNotFound, setIsNotFound] = React.useState(false);
  const [activeTab, setActiveTab] = React.useState("details");
  const [memberRows, setMemberRows] = React.useState([]);
  const [memberPage, setMemberPage] = React.useState(1);
  const [memberTotal, setMemberTotal] = React.useState(0);
  const [memberTotalPages, setMemberTotalPages] = React.useState(1);
  const [memberSorting, setMemberSorting] = React.useState([{ id: "displayName", desc: false }]);
  const [memberSearch, setMemberSearch] = React.useState("");
  const [membersLoading, setMembersLoading] = React.useState(false);
  const [memberReloadToken, setMemberReloadToken] = React.useState(0);
  const memberLabels = React.useMemo(() => ({
    title: t("staff.teams.tabs.members", "Team members"),
    description: t("staff.teamMembers.page.description", "Manage employees and their team assignments."),
    table: {
      name: t("staff.teamMembers.table.name", "Name"),
      user: t("staff.teamMembers.table.user", "User"),
      roles: t("staff.teamMembers.table.roles", "Roles"),
      tags: t("staff.teamMembers.table.tags", "Tags"),
      active: t("staff.teamMembers.table.active", "Active"),
      updatedAt: t("staff.teamMembers.table.updatedAt", "Updated"),
      empty: t("staff.teamMembers.table.empty", "No team members yet."),
      search: t("staff.teamMembers.table.search", "Search team members...")
    },
    actions: {
      add: t("staff.teamMembers.actions.add", "Add team member"),
      edit: t("staff.teamMembers.actions.edit", "Edit"),
      unassign: t("staff.teamMembers.actions.unassign", "Unassign"),
      refresh: t("staff.teamMembers.actions.refresh", "Refresh")
    },
    messages: {
      unassigned: t("staff.teamMembers.messages.unassigned", "Team member unassigned.")
    },
    errors: {
      load: t("staff.teamMembers.errors.load", "Failed to load team members."),
      unassign: t("staff.teamMembers.errors.unassign", "Failed to unassign team member.")
    },
    tabs: {
      details: t("staff.teams.tabs.details", "Details"),
      members: t("staff.teams.tabs.members", "Team members"),
      label: t("staff.teams.tabs.label", "Team sections")
    }
  }), [t]);
  const memberColumns = React.useMemo(() => [
    {
      accessorKey: "displayName",
      header: memberLabels.table.name,
      meta: { priority: 1, sticky: true },
      cell: ({ row }) => /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
        /* @__PURE__ */ jsx("span", { className: "font-medium", children: row.original.displayName }),
        row.original.description ? /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground line-clamp-2", children: row.original.description }) : null
      ] })
    },
    {
      accessorKey: "userEmail",
      header: memberLabels.table.user,
      meta: { priority: 2 },
      cell: ({ row }) => row.original.userEmail ? /* @__PURE__ */ jsx("span", { className: "text-sm", children: row.original.userEmail }) : /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "-" })
    },
    {
      accessorKey: "roleNames",
      header: memberLabels.table.roles,
      meta: { priority: 3 },
      cell: ({ row }) => row.original.roleNames.length ? /* @__PURE__ */ jsx("span", { className: "text-sm", children: row.original.roleNames.join(", ") }) : /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "-" })
    },
    {
      accessorKey: "tags",
      header: memberLabels.table.tags,
      meta: { priority: 4 },
      cell: ({ row }) => row.original.tags.length ? /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: row.original.tags.join(", ") }) : /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "-" })
    },
    {
      accessorKey: "isActive",
      header: memberLabels.table.active,
      meta: { priority: 5 },
      cell: ({ row }) => /* @__PURE__ */ jsx(BooleanIcon, { value: row.original.isActive })
    },
    {
      accessorKey: "updatedAt",
      header: memberLabels.table.updatedAt,
      meta: { priority: 6 },
      cell: ({ row }) => row.original.updatedAt ? /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: formatDateTime(row.original.updatedAt) }) : /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "-" })
    }
  ], [
    memberLabels.table.active,
    memberLabels.table.name,
    memberLabels.table.roles,
    memberLabels.table.tags,
    memberLabels.table.updatedAt,
    memberLabels.table.user
  ]);
  React.useEffect(() => {
    if (!teamId) return;
    const teamIdValue = teamId;
    let cancelled = false;
    async function loadTeam() {
      if (!cancelled) {
        setError(null);
        setIsNotFound(false);
      }
      try {
        const params2 = new URLSearchParams({ page: "1", pageSize: "1", ids: teamIdValue });
        const payload = await readApiResultOrThrow(
          `/api/staff/teams?${params2.toString()}`,
          void 0,
          { errorMessage: t("staff.teams.errors.load", "Failed to load team.") }
        );
        const record = Array.isArray(payload.items) ? payload.items[0] : null;
        if (!record) {
          if (!cancelled) setIsNotFound(true);
          return;
        }
        const customFields = extractCustomFieldEntries(record);
        const isActive = typeof record.isActive === "boolean" ? record.isActive : typeof record.is_active === "boolean" ? record.is_active : true;
        if (!cancelled) {
          setInitialValues({
            id: record.id,
            name: record.name ?? "",
            description: record.description ?? "",
            isActive,
            updatedAt: typeof record.updatedAt === "string" ? record.updatedAt : typeof record.updated_at === "string" ? record.updated_at : null,
            ...customFields
          });
        }
      } catch (err) {
        if (!cancelled) {
          if (err.status === 404) {
            setIsNotFound(true);
          } else {
            const message = err instanceof Error ? err.message : t("staff.teams.errors.load", "Failed to load team.");
            setError(message);
          }
        }
      }
    }
    loadTeam();
    return () => {
      cancelled = true;
    };
  }, [teamId, t]);
  React.useEffect(() => {
    if (!searchParams) return;
    const tabParam = searchParams.get("tab");
    if (tabParam === "members") {
      setActiveTab("members");
    }
  }, [searchParams]);
  const loadTeamMembers = React.useCallback(async () => {
    if (!teamId) return;
    setMembersLoading(true);
    try {
      const params2 = new URLSearchParams({
        page: String(memberPage),
        pageSize: String(TEAM_MEMBERS_PAGE_SIZE),
        teamId
      });
      const sort = memberSorting[0];
      if (sort?.id) {
        params2.set("sortField", sort.id);
        params2.set("sortDir", sort.desc ? "desc" : "asc");
      }
      if (memberSearch.trim()) params2.set("search", memberSearch.trim());
      const payload = await readApiResultOrThrow(
        `/api/staff/team-members?${params2.toString()}`,
        void 0,
        { errorMessage: memberLabels.errors.load, fallback: { items: [], total: 0, totalPages: 1 } }
      );
      const items = Array.isArray(payload.items) ? payload.items : [];
      setMemberRows(items.map(mapApiTeamMember));
      setMemberTotal(typeof payload.total === "number" ? payload.total : items.length);
      setMemberTotalPages(
        typeof payload.totalPages === "number" ? payload.totalPages : Math.max(1, Math.ceil(items.length / TEAM_MEMBERS_PAGE_SIZE))
      );
    } catch (error2) {
      logger.error("staff.teams.team-members.list", { err: error2 });
      flash(memberLabels.errors.load, "error");
    } finally {
      setMembersLoading(false);
    }
  }, [memberLabels.errors.load, memberPage, memberSearch, memberSorting, teamId]);
  React.useEffect(() => {
    if (activeTab !== "members") return;
    void loadTeamMembers();
  }, [activeTab, loadTeamMembers, memberReloadToken, scopeVersion]);
  const handleMemberSearchChange = React.useCallback((value) => {
    setMemberSearch(value);
    setMemberPage(1);
  }, []);
  const handleMemberRefresh = React.useCallback(() => {
    setMemberReloadToken((token) => token + 1);
  }, []);
  const handleUnassignMember = React.useCallback(async (entry) => {
    if (!teamId || entry.teamId !== teamId) return;
    try {
      const headers = buildOptimisticLockHeader(entry.updatedAt);
      await withScopedApiRequestHeaders(headers, () => updateCrud("staff/team-members", { id: entry.id, teamId: null }, { errorMessage: memberLabels.errors.unassign }));
      flash(memberLabels.messages.unassigned, "success");
      handleMemberRefresh();
    } catch (error2) {
      logger.error("staff.teams.team-members.unassign", { err: error2 });
      flash(memberLabels.errors.unassign, "error");
    }
  }, [handleMemberRefresh, memberLabels.errors.unassign, memberLabels.messages.unassigned, teamId]);
  const handleSubmit = React.useCallback(async (values) => {
    if (!teamId) return;
    const payload = buildTeamPayload(values, { id: teamId });
    await updateCrud("staff/teams", payload, {
      errorMessage: t("staff.teams.errors.save", "Failed to save team.")
    });
    flash(t("staff.teams.messages.saved", "Team saved."), "success");
  }, [teamId, t]);
  const handleDelete = React.useCallback(async () => {
    if (!teamId) return;
    await deleteCrud("staff/teams", teamId, {
      errorMessage: t("staff.teams.errors.delete", "Failed to delete team.")
    });
    router.push("/backend/staff/teams");
  }, [teamId, router, t]);
  useSetCurrentRecordInjectionContext(
    buildRecordInjectionContext({
      resourceKind: "staff.team",
      resourceId: teamId || null,
      updatedAt: initialValues?.updatedAt ?? null,
      data: initialValues,
      path: pathname
    })
  );
  if (isNotFound) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      RecordNotFoundState,
      {
        label: t("staff.teams.errors.notFound", "Team not found."),
        backHref: "/backend/staff/teams",
        backLabel: t("staff.teams.actions.backToList", "Back to teams")
      }
    ) }) });
  }
  if (error && !initialValues) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(ErrorMessage, { label: error }) }) });
  }
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsx("div", { className: "border-b", children: /* @__PURE__ */ jsx("nav", { className: "flex flex-wrap items-center gap-5 text-sm", "aria-label": memberLabels.tabs.label, children: [
      { id: "details", label: memberLabels.tabs.details },
      { id: "members", label: memberLabels.tabs.members }
    ].map((tab) => /* @__PURE__ */ jsx(
      "button",
      {
        type: "button",
        role: "tab",
        "aria-selected": activeTab === tab.id,
        onClick: () => setActiveTab(tab.id),
        className: `relative -mb-px border-b-2 px-0 py-2 text-sm font-medium transition-colors ${activeTab === tab.id ? "border-accent-indigo text-foreground" : "border-transparent text-muted-foreground hover:text-foreground"}`,
        children: tab.label
      },
      tab.id
    )) }) }),
    activeTab === "details" ? /* @__PURE__ */ jsx(
      TeamForm,
      {
        title: t("staff.teams.form.editTitle", "Edit team"),
        backHref: "/backend/staff/teams",
        cancelHref: "/backend/staff/teams",
        initialValues: initialValues ?? { name: "", description: "", isActive: true },
        onSubmit: handleSubmit,
        onDelete: handleDelete,
        isLoading: !initialValues,
        loadingMessage: t("staff.teams.form.loading", "Loading team..."),
        extraActions: teamId ? /* @__PURE__ */ jsx(
          SendObjectMessageDialog,
          {
            object: {
              entityModule: "staff",
              entityType: "team",
              entityId: teamId,
              previewData: { title: initialValues?.name ?? "" }
            },
            viewHref: `/backend/staff/teams/${teamId}/edit`
          }
        ) : void 0
      }
    ) : /* @__PURE__ */ jsx(
      DataTable,
      {
        title: memberLabels.title,
        data: memberRows,
        columns: memberColumns,
        isLoading: membersLoading,
        searchValue: memberSearch,
        onSearchChange: handleMemberSearchChange,
        searchPlaceholder: memberLabels.table.search,
        emptyState: /* @__PURE__ */ jsx("p", { className: "py-8 text-center text-sm text-muted-foreground", children: memberLabels.table.empty }),
        actions: /* @__PURE__ */ jsx(Button, { asChild: true, size: "sm", children: /* @__PURE__ */ jsxs(Link, { href: `/backend/staff/team-members/create?teamId=${encodeURIComponent(teamId ?? "")}`, children: [
          /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4", "aria-hidden": true }),
          memberLabels.actions.add
        ] }) }),
        refreshButton: {
          label: memberLabels.actions.refresh,
          onRefresh: handleMemberRefresh,
          isRefreshing: membersLoading
        },
        sortable: true,
        sorting: memberSorting,
        onSortingChange: setMemberSorting,
        pagination: {
          page: memberPage,
          pageSize: TEAM_MEMBERS_PAGE_SIZE,
          total: memberTotal,
          totalPages: memberTotalPages,
          onPageChange: setMemberPage
        },
        rowActions: (row) => /* @__PURE__ */ jsx(
          RowActions,
          {
            items: [
              { id: "edit", label: memberLabels.actions.edit, onSelect: () => {
                router.push(`/backend/staff/team-members/${row.id}`);
              } },
              { id: "unassign", label: memberLabels.actions.unassign, onSelect: () => {
                void handleUnassignMember(row);
              } }
            ]
          }
        )
      }
    )
  ] }) }) });
}
function mapApiTeamMember(item) {
  const id = typeof item.id === "string" ? item.id : "";
  const displayName = typeof item.displayName === "string" ? item.displayName : typeof item.display_name === "string" ? item.display_name : id;
  const description = typeof item.description === "string" && item.description.trim().length ? item.description.trim() : null;
  const user = item.user && typeof item.user === "object" ? item.user : null;
  const userEmail = user && typeof user.email === "string" && user.email.length ? user.email : null;
  const roleNames = Array.isArray(item.roleNames) ? item.roleNames.filter((value) => typeof value === "string") : [];
  const tags = Array.isArray(item.tags) ? item.tags.filter((value) => typeof value === "string") : [];
  const updatedAt = typeof item.updatedAt === "string" ? item.updatedAt : typeof item.updated_at === "string" ? item.updated_at : null;
  const isActive = typeof item.isActive === "boolean" ? item.isActive : typeof item.is_active === "boolean" ? item.is_active : true;
  const teamId = typeof item.teamId === "string" ? item.teamId : typeof item.team_id === "string" ? item.team_id : null;
  return withDataTableNamespaces({
    id,
    displayName,
    description,
    userEmail,
    roleNames,
    tags,
    isActive,
    updatedAt,
    teamId
  }, item);
}
export {
  StaffTeamEditPage as default
};
//# sourceMappingURL=page.js.map
