"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 { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { DataTable, withDataTableNamespaces } from "@open-mercato/ui/backend/DataTable";
import { RowActions } from "@open-mercato/ui/backend/RowActions";
import { markdownToPlainText } from "@open-mercato/ui/backend/markdown/markdownToPlainText";
import { Button } from "@open-mercato/ui/primitives/button";
import { BooleanIcon } from "@open-mercato/ui/backend/ValueIcons";
import { readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { surfaceRecordConflict } from "@open-mercato/ui/backend/conflicts";
import { deleteCrud } from "@open-mercato/ui/backend/utils/crud";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { ListEmptyState } from "@open-mercato/ui/backend/filters/ListEmptyState";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Users } from "lucide-react";
import { formatDateTime } from "@open-mercato/shared/lib/time";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("staff");
const PAGE_SIZE = 50;
function StaffTeamsPage() {
  const t = useT();
  const router = useRouter();
  const scopeVersion = useOrganizationScopeVersion();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const [rows, setRows] = React.useState([]);
  const [page, setPage] = React.useState(1);
  const [total, setTotal] = React.useState(0);
  const [totalPages, setTotalPages] = React.useState(1);
  const [sorting, setSorting] = React.useState([{ id: "name", desc: false }]);
  const [search, setSearch] = React.useState("");
  const [isLoading, setIsLoading] = React.useState(true);
  const [reloadToken, setReloadToken] = React.useState(0);
  const labels = React.useMemo(() => ({
    title: t("staff.teams.page.title", "Teams"),
    description: t("staff.teams.page.description", "Group team members and roles."),
    table: {
      name: t("staff.teams.table.name", "Name"),
      description: t("staff.teams.table.description", "Description"),
      active: t("staff.teams.table.active", "Active"),
      members: t("staff.teams.table.members", "Team members"),
      updatedAt: t("staff.teams.table.updatedAt", "Updated"),
      empty: t("staff.teams.table.empty", "No teams yet."),
      search: t("staff.teams.table.search", "Search teams...")
    },
    actions: {
      add: t("staff.teams.actions.add", "Add team"),
      edit: t("staff.teams.actions.edit", "Edit"),
      delete: t("staff.teams.actions.delete", "Delete"),
      deleteConfirm: t("staff.teams.actions.deleteConfirm", 'Delete team "{{name}}"?'),
      showMembers: t("staff.teams.actions.showMembers", "Show team members ({{count}})"),
      refresh: t("staff.teams.actions.refresh", "Refresh")
    },
    messages: {
      deleted: t("staff.teams.messages.deleted", "Team deleted.")
    },
    errors: {
      load: t("staff.teams.errors.load", "Failed to load teams."),
      delete: t("staff.teams.errors.delete", "Failed to delete team."),
      deleteAssigned: t("staff.teams.errors.deleteAssigned", "Team has assigned members and cannot be deleted.")
    }
  }), [t]);
  const columns = React.useMemo(() => [
    {
      accessorKey: "name",
      header: labels.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.name }),
        row.original.description ? /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground line-clamp-2", children: markdownToPlainText(row.original.description) }) : null
      ] })
    },
    {
      accessorKey: "description",
      header: labels.table.description,
      meta: { priority: 4 },
      cell: ({ row }) => row.original.description ? /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground line-clamp-2", children: markdownToPlainText(row.original.description) }) : /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "-" })
    },
    {
      accessorKey: "isActive",
      header: labels.table.active,
      meta: { priority: 2 },
      cell: ({ row }) => /* @__PURE__ */ jsx(BooleanIcon, { value: row.original.isActive })
    },
    {
      accessorKey: "memberCount",
      header: () => /* @__PURE__ */ jsx("span", { className: "inline-block min-w-[250px]", children: labels.table.members }),
      meta: { priority: 3 },
      enableSorting: false,
      cell: ({ row }) => /* @__PURE__ */ jsxs(
        Link,
        {
          className: "inline-flex min-w-[220px] items-center gap-2 text-sm text-muted-foreground hover:text-foreground",
          href: `/backend/staff/team-members?teamId=${encodeURIComponent(row.original.id)}`,
          onClick: (event) => event.stopPropagation(),
          children: [
            /* @__PURE__ */ jsx(Users, { className: "h-4 w-4", "aria-hidden": true }),
            labels.actions.showMembers.replace("{{count}}", String(row.original.memberCount))
          ]
        }
      )
    },
    {
      accessorKey: "updatedAt",
      header: labels.table.updatedAt,
      meta: { priority: 5 },
      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: "-" })
    }
  ], [
    labels.actions.showMembers,
    labels.table.active,
    labels.table.description,
    labels.table.members,
    labels.table.name,
    labels.table.updatedAt
  ]);
  const loadTeams = React.useCallback(async () => {
    setIsLoading(true);
    try {
      const params = new URLSearchParams({
        page: String(page),
        pageSize: String(PAGE_SIZE)
      });
      const sort = sorting[0];
      if (sort?.id) {
        params.set("sortField", sort.id);
        params.set("sortDir", sort.desc ? "desc" : "asc");
      }
      if (search.trim()) params.set("search", search.trim());
      const payload = await readApiResultOrThrow(
        `/api/staff/teams?${params.toString()}`,
        void 0,
        { errorMessage: labels.errors.load, fallback: { items: [], total: 0, totalPages: 1 } }
      );
      const items = Array.isArray(payload.items) ? payload.items : [];
      setRows(items.map(mapApiTeam));
      setTotal(typeof payload.total === "number" ? payload.total : items.length);
      setTotalPages(typeof payload.totalPages === "number" ? payload.totalPages : Math.max(1, Math.ceil(items.length / PAGE_SIZE)));
    } catch (error) {
      logger.error("staff.teams.list", { err: error });
      flash(labels.errors.load, "error");
    } finally {
      setIsLoading(false);
    }
  }, [labels.errors.load, page, search, sorting]);
  React.useEffect(() => {
    void loadTeams();
  }, [loadTeams, scopeVersion, reloadToken]);
  const handleSearchChange = React.useCallback((value) => {
    setSearch(value);
    setPage(1);
  }, []);
  const handleRefresh = React.useCallback(() => {
    setReloadToken((token) => token + 1);
  }, []);
  const handleDelete = React.useCallback(async (entry) => {
    if (entry.memberCount > 0) {
      flash(labels.errors.deleteAssigned, "error");
      return;
    }
    const message = labels.actions.deleteConfirm.replace("{{name}}", entry.name);
    const confirmed = await confirm({
      title: labels.actions.delete,
      text: message,
      variant: "destructive"
    });
    if (!confirmed) return;
    try {
      await withScopedApiRequestHeaders(
        buildOptimisticLockHeader(entry.updatedAt),
        () => deleteCrud("staff/teams", entry.id, { errorMessage: labels.errors.delete })
      );
      flash(labels.messages.deleted, "success");
      handleRefresh();
    } catch (error) {
      if (surfaceRecordConflict(error, t)) {
        handleRefresh();
        return;
      }
      logger.error("staff.teams.delete", { err: error });
      flash(labels.errors.delete, "error");
    }
  }, [confirm, handleRefresh, labels.actions.deleteConfirm, labels.actions.delete, labels.errors.delete, labels.errors.deleteAssigned, labels.messages.deleted, t]);
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      DataTable,
      {
        title: labels.title,
        data: rows,
        columns,
        isLoading,
        searchValue: search,
        onSearchChange: handleSearchChange,
        searchPlaceholder: labels.table.search,
        emptyState: /* @__PURE__ */ jsx(
          ListEmptyState,
          {
            entityName: labels.title,
            createHref: "/backend/staff/teams/create",
            createLabel: labels.actions.add
          }
        ),
        actions: /* @__PURE__ */ jsx(Button, { asChild: true, size: "sm", children: /* @__PURE__ */ jsx(Link, { href: "/backend/staff/teams/create", children: labels.actions.add }) }),
        refreshButton: {
          label: labels.actions.refresh,
          onRefresh: handleRefresh,
          isRefreshing: isLoading
        },
        sortable: true,
        sorting,
        onSortingChange: setSorting,
        pagination: {
          page,
          pageSize: PAGE_SIZE,
          total,
          totalPages,
          onPageChange: setPage
        },
        rowActions: (row) => /* @__PURE__ */ jsx(
          RowActions,
          {
            items: [
              { id: "edit", label: labels.actions.edit, href: `/backend/staff/teams/${row.id}/edit` },
              ...row.memberCount > 0 ? [] : [{ id: "delete", label: labels.actions.delete, destructive: true, onSelect: () => {
                void handleDelete(row);
              } }]
            ]
          }
        ),
        onRowClick: (row) => router.push(`/backend/staff/teams/${row.id}/edit`)
      }
    ) }),
    ConfirmDialogElement
  ] });
}
function mapApiTeam(item) {
  const id = typeof item.id === "string" ? item.id : "";
  const name = typeof item.name === "string" ? item.name : id;
  const description = typeof item.description === "string" && item.description.trim().length ? item.description.trim() : null;
  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 memberCount = typeof item.memberCount === "number" ? item.memberCount : typeof item.member_count === "number" ? item.member_count : 0;
  return withDataTableNamespaces({ id, name, description, isActive, updatedAt, memberCount }, item);
}
export {
  StaffTeamsPage as default
};
//# sourceMappingURL=page.js.map
