"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { useRouter, useParams, usePathname } from "next/navigation";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { Button } from "@open-mercato/ui/primitives/button";
import { apiFetch, withScopedApiHeaders } from "@open-mercato/ui/backend/utils/api";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { buildRecordInjectionContext, useSetCurrentRecordInjectionContext } from "@open-mercato/ui/backend/injection/recordContext";
import { readJsonSafe } from "@open-mercato/ui/backend/utils/serverErrors";
import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useOrganizationScopeDetail } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { z } from "zod";
import { RuleSetMembers } from "@open-mercato/core/modules/business_rules/components/RuleSetMembers";
const ruleSetFormSchema = z.object({
  setId: z.string().min(1).max(50),
  setName: z.string().min(1).max(200),
  description: z.string().max(5e3).optional().nullable(),
  enabled: z.boolean().optional()
});
function EditRuleSetPage() {
  const router = useRouter();
  const params = useParams();
  const pathname = usePathname();
  let setId;
  if (params?.slug && Array.isArray(params.slug)) {
    setId = params.slug[1];
  } else if (params?.id) {
    setId = Array.isArray(params.id) ? params.id[0] : params.id;
  }
  const t = useT();
  const { organizationId, tenantId } = useOrganizationScopeDetail();
  const queryClient = useQueryClient();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const { data: ruleSet, isLoading, error } = useQuery({
    queryKey: ["business-rules", "sets", setId],
    queryFn: async () => {
      const response = await apiFetch(`/api/business_rules/sets/${setId}`);
      if (!response.ok) {
        throw new Error(t("business_rules.sets.errors.fetchFailed"));
      }
      const result = await response.json();
      return result;
    },
    enabled: !!setId
  });
  const handleSubmit = async (values) => {
    const payload = {
      id: setId,
      ...values
    };
    const updateSet = () => apiFetch("/api/business_rules/sets", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload)
    });
    const headers = buildOptimisticLockHeader(ruleSet?.updatedAt ?? null);
    const response = Object.keys(headers).length ? await withScopedApiHeaders(headers, updateSet) : await updateSet();
    if (!response.ok) {
      const body = await readJsonSafe(response) ?? {};
      const message = typeof body.error === "string" && body.error || typeof body.message === "string" && body.message || t("business_rules.sets.errors.updateFailed");
      throw new CrudHttpError(response.status, { ...body, error: message });
    }
    flash(t("business_rules.sets.messages.updated"), "success");
    queryClient.invalidateQueries({ queryKey: ["business-rules", "sets", setId] });
  };
  const handleAddMember = async (ruleId, sequence) => {
    const result = await apiCall(`/api/business_rules/sets/${setId}/members`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        ruleId,
        sequence,
        enabled: true
      })
    });
    if (result.ok) {
      flash(t("business_rules.sets.members.messages.added"), "success");
      queryClient.invalidateQueries({ queryKey: ["business-rules", "sets", setId] });
    } else {
      const error2 = result.result;
      if (error2?.error?.includes("duplicate") || error2?.message?.includes("exists")) {
        flash(t("business_rules.sets.members.messages.alreadyExists"), "error");
      } else {
        flash(t("business_rules.sets.members.messages.addFailed"), "error");
      }
    }
  };
  const handleUpdateMember = async (memberId, updates) => {
    const result = await apiCall(`/api/business_rules/sets/${setId}/members`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        memberId,
        ...updates
      })
    });
    if (result.ok) {
      flash(t("business_rules.sets.members.messages.updated"), "success");
      queryClient.invalidateQueries({ queryKey: ["business-rules", "sets", setId] });
    } else {
      flash(t("business_rules.sets.members.messages.updateFailed"), "error");
    }
  };
  const handleRemoveMember = async (memberId, ruleName) => {
    const confirmed = await confirm({
      title: t("business_rules.sets.members.confirm.remove", { name: ruleName }),
      variant: "destructive"
    });
    if (!confirmed) return;
    const result = await apiCall(`/api/business_rules/sets/${setId}/members?memberId=${memberId}`, {
      method: "DELETE"
    });
    if (result.ok) {
      flash(t("business_rules.sets.members.messages.removed"), "success");
      queryClient.invalidateQueries({ queryKey: ["business-rules", "sets", setId] });
    } else {
      flash(t("business_rules.sets.members.messages.removeFailed"), "error");
    }
  };
  const fields = React.useMemo(() => [
    {
      id: "setId",
      label: t("business_rules.sets.form.setId"),
      type: "text",
      required: true,
      placeholder: t("business_rules.sets.form.placeholders.setId"),
      description: t("business_rules.sets.form.descriptions.setId")
    },
    {
      id: "setName",
      label: t("business_rules.sets.form.setName"),
      type: "text",
      required: true,
      placeholder: t("business_rules.sets.form.placeholders.setName")
    },
    {
      id: "description",
      label: t("business_rules.sets.form.description"),
      type: "textarea",
      placeholder: t("business_rules.sets.form.placeholders.description")
    },
    {
      id: "enabled",
      label: t("business_rules.sets.form.enabled"),
      type: "checkbox",
      description: t("business_rules.sets.form.descriptions.enabled")
    }
  ], [t]);
  const initialValues = React.useMemo(() => {
    if (!ruleSet) return {};
    return {
      setId: ruleSet.setId,
      setName: ruleSet.setName,
      description: ruleSet.description,
      enabled: ruleSet.enabled
    };
  }, [ruleSet]);
  const formGroups = React.useMemo(() => {
    if (!ruleSet) return [];
    return [
      {
        id: "details",
        title: t("business_rules.sets.edit.detailsSection"),
        column: 1,
        fields: ["setId", "setName", "description", "enabled"]
      },
      {
        id: "members",
        title: t("business_rules.sets.edit.membersSection"),
        column: 1,
        component: () => /* @__PURE__ */ jsx(
          RuleSetMembers,
          {
            members: ruleSet.members,
            onAdd: handleAddMember,
            onUpdate: handleUpdateMember,
            onRemove: handleRemoveMember
          }
        )
      }
    ];
  }, [t, ruleSet, handleAddMember, handleUpdateMember, handleRemoveMember]);
  useSetCurrentRecordInjectionContext(
    buildRecordInjectionContext({
      resourceKind: "business_rules.ruleSet",
      resourceId: setId ?? null,
      updatedAt: ruleSet?.updatedAt ?? null,
      data: ruleSet ?? null,
      path: pathname
    })
  );
  if (isLoading) {
    return /* @__PURE__ */ jsxs(Page, { children: [
      /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "flex h-[50vh] flex-col items-center justify-center gap-2 text-muted-foreground", children: [
        /* @__PURE__ */ jsx(Spinner, { className: "h-6 w-6" }),
        /* @__PURE__ */ jsx("span", { children: t("business_rules.sets.edit.loading") })
      ] }) }),
      ConfirmDialogElement
    ] });
  }
  if (error || !ruleSet) {
    return /* @__PURE__ */ jsxs(Page, { children: [
      /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "flex h-[50vh] flex-col items-center justify-center gap-2 text-muted-foreground", children: [
        /* @__PURE__ */ jsx("p", { children: t("business_rules.sets.messages.loadFailed") }),
        /* @__PURE__ */ jsx(Button, { asChild: true, variant: "outline", children: /* @__PURE__ */ jsx(Link, { href: "/backend/sets", children: t("business_rules.sets.backToList") }) })
      ] }) }),
      ConfirmDialogElement
    ] });
  }
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      CrudForm,
      {
        title: t("business_rules.sets.edit.title"),
        backHref: "/backend/sets",
        schema: ruleSetFormSchema,
        fields,
        initialValues,
        optimisticLockUpdatedAt: ruleSet.updatedAt,
        onSubmit: handleSubmit,
        cancelHref: "/backend/sets",
        submitLabel: t("business_rules.sets.form.update"),
        groups: formGroups
      }
    ) }),
    ConfirmDialogElement
  ] });
}
export {
  EditRuleSetPage as default
};
//# sourceMappingURL=page.js.map
