"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 { markdownToPlainText } from "@open-mercato/ui/backend/markdown/markdownToPlainText";
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 { readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { deleteCrud } from "@open-mercato/ui/backend/utils/crud";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { normalizeCrudServerError } from "@open-mercato/ui/backend/utils/serverErrors";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { formatDateTime } from "@open-mercato/shared/lib/time";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("planner").child({ component: "availability-rulesets-page" });
const PAGE_SIZE = 50;
const SUBTEXT_CLASSNAME = "line-clamp-2 text-xs text-muted-foreground";
function PlannerAvailabilityRuleSetsPage() {
  const t = useT();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const router = useRouter();
  const scopeVersion = useOrganizationScopeVersion();
  const mutationContextId = "planner-availability-rule-sets";
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: mutationContextId,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const mutationContext = React.useMemo(
    () => ({
      formId: mutationContextId,
      resourceKind: "planner.availability_rule_set",
      retryLastMutation
    }),
    [mutationContextId, retryLastMutation]
  );
  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("planner.availabilityRuleSets.page.title", "Availability schedules"),
    description: t("planner.availabilityRuleSets.page.description", "Manage shared availability rulesets."),
    table: {
      name: t("planner.availabilityRuleSets.table.name", "Name"),
      timezone: t("planner.availabilityRuleSets.table.timezone", "Timezone"),
      updatedAt: t("planner.availabilityRuleSets.table.updatedAt", "Updated"),
      empty: t("planner.availabilityRuleSets.table.empty", "No schedules yet."),
      search: t("planner.availabilityRuleSets.table.search", "Search schedules...")
    },
    actions: {
      add: t("planner.availabilityRuleSets.actions.add", "New schedule"),
      edit: t("planner.availabilityRuleSets.actions.edit", "Edit"),
      delete: t("planner.availabilityRuleSets.actions.delete", "Delete"),
      deleteConfirm: t("planner.availabilityRuleSets.actions.deleteConfirm", 'Delete schedule "{{name}}"?'),
      refresh: t("planner.availabilityRuleSets.actions.refresh", "Refresh")
    },
    messages: {
      deleted: t("planner.availabilityRuleSets.messages.deleted", "Schedule deleted.")
    },
    errors: {
      load: t("planner.availabilityRuleSets.errors.load", "Failed to load schedules."),
      delete: t("planner.availabilityRuleSets.errors.delete", "Failed to delete schedule.")
    }
  }), [t]);
  const loadRuleSets = 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/planner/availability-rule-sets?${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(mapRuleSet));
      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("Failed to list availability rule sets", { err: error });
      flash(labels.errors.load, "error");
    } finally {
      setIsLoading(false);
    }
  }, [labels.errors.load, page, search, sorting]);
  React.useEffect(() => {
    void loadRuleSets();
  }, [loadRuleSets, 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) => {
    const message = labels.actions.deleteConfirm.replace("{{name}}", entry.name);
    const confirmed = await confirm({
      title: message,
      variant: "default"
    });
    if (!confirmed) return;
    try {
      await runMutation({
        operation: () => withScopedApiRequestHeaders(buildOptimisticLockHeader(entry.updatedAt), () => deleteCrud("planner/availability-rule-sets", entry.id, { errorMessage: labels.errors.delete })),
        context: mutationContext,
        mutationPayload: { action: "delete", id: entry.id }
      });
      flash(labels.messages.deleted, "success");
      handleRefresh();
    } catch (error) {
      logger.error("Failed to delete availability rule set", { err: error });
      const normalized = normalizeCrudServerError(error);
      flash(normalized.message ?? labels.errors.delete, "error");
    }
  }, [confirm, handleRefresh, labels.actions.deleteConfirm, labels.errors.delete, labels.messages.deleted, mutationContext, runMutation]);
  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: SUBTEXT_CLASSNAME, children: markdownToPlainText(row.original.description) }) : null
      ] })
    },
    {
      accessorKey: "timezone",
      header: labels.table.timezone,
      meta: { priority: 2 },
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "text-sm", children: row.original.timezone })
    },
    {
      accessorKey: "updatedAt",
      header: labels.table.updatedAt,
      meta: { priority: 3 },
      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.table.name, labels.table.timezone, labels.table.updatedAt]);
  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("p", { className: "py-8 text-center text-sm text-muted-foreground", children: labels.table.empty }),
        actions: /* @__PURE__ */ jsx(Button, { asChild: true, size: "sm", children: /* @__PURE__ */ jsx(Link, { href: "/backend/planner/availability-rulesets/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/planner/availability-rulesets/${row.id}` },
              { id: "delete", label: labels.actions.delete, destructive: true, onSelect: () => {
                void handleDelete(row);
              } }
            ]
          }
        ),
        onRowClick: (row) => router.push(`/backend/planner/availability-rulesets/${row.id}`)
      }
    ) }),
    ConfirmDialogElement
  ] });
}
function mapRuleSet(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 : null;
  const timezone = typeof item.timezone === "string" ? item.timezone : "UTC";
  const updatedAt = typeof item.updatedAt === "string" ? item.updatedAt : typeof item.updated_at === "string" ? item.updated_at : null;
  return withDataTableNamespaces({
    id,
    name,
    description,
    timezone,
    updatedAt
  }, item);
}
export {
  PlannerAvailabilityRuleSetsPage as default
};
//# sourceMappingURL=page.js.map
