"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useRouter, useParams, usePathname } from "next/navigation";
import { useQuery } 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 { Alert, AlertDescription } from "@open-mercato/ui/primitives/alert";
import { apiFetch, withScopedApiHeaders } from "@open-mercato/ui/backend/utils/api";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { buildRecordInjectionContext, useSetCurrentRecordInjectionContext } from "@open-mercato/ui/backend/injection/recordContext";
import { ErrorMessage, RecordNotFoundState } from "@open-mercato/ui/backend/detail";
import { readJsonSafe } from "@open-mercato/ui/backend/utils/serverErrors";
import { formatWorkflowValidationError } from "../../../lib/format-validation-error.js";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import {
  workflowDefinitionFormSchema,
  createFormGroups,
  createFieldDefinitions,
  parseWorkflowToFormValues,
  buildWorkflowPayload
} from "../../../components/formConfig.js";
import { StepsEditor } from "../../../components/StepsEditor.js";
import { TransitionsEditor } from "../../../components/TransitionsEditor.js";
import { DefinitionTriggersEditor } from "../../../components/DefinitionTriggersEditor.js";
import { MobileDefinitionDetail } from "../../../components/mobile/MobileDefinitionDetail.js";
import { useIsMobile } from "@open-mercato/ui/hooks/useIsMobile";
function EditWorkflowDefinitionPage() {
  const router = useRouter();
  const params = useParams();
  const pathname = usePathname();
  const t = useT();
  const isMobile = useIsMobile();
  let definitionId;
  if (params?.slug && Array.isArray(params.slug)) {
    definitionId = params.slug[1];
  } else if (params?.id) {
    definitionId = Array.isArray(params.id) ? params.id[0] : params.id;
  }
  const { data: definition, isLoading, error } = useQuery({
    queryKey: ["workflow-definition", definitionId],
    queryFn: async () => {
      const response = await apiFetch(`/api/workflows/definitions/${definitionId}`);
      if (!response.ok) {
        const err = new Error(t("workflows.errors.fetchFailed"));
        err.status = response.status;
        throw err;
      }
      const result = await response.json();
      return result.data;
    },
    enabled: !!definitionId,
    retry: (failureCount, err) => {
      if (err.status === 404) return false;
      return failureCount < 2;
    }
  });
  const isNotFound = error?.status === 404;
  const initialValues = React.useMemo(() => {
    if (definition) {
      return parseWorkflowToFormValues(definition);
    }
    return null;
  }, [definition]);
  const [triggers, setTriggers] = React.useState([]);
  React.useEffect(() => {
    setTriggers(initialValues?.triggers ?? []);
  }, [initialValues]);
  const source = definition?.source;
  const isCodeOnly = source === "code";
  const isCodeOverride = source === "code_override";
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const mutationContextId = React.useMemo(
    () => `workflows.definitions.detail:${definitionId ?? "unknown"}`,
    [definitionId]
  );
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: mutationContextId
  });
  const handleSubmit = async (values) => {
    const payload = buildWorkflowPayload({ ...values, triggers });
    const optimisticLockHeader = buildOptimisticLockHeader(
      typeof definition?.updatedAt === "string" ? definition.updatedAt : null
    );
    await runMutation({
      operation: async () => {
        const updateDefinition = () => apiFetch(`/api/workflows/definitions/${definitionId}`, {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload)
        });
        const response = Object.keys(optimisticLockHeader).length > 0 ? await withScopedApiHeaders(optimisticLockHeader, updateDefinition) : await updateDefinition();
        if (!response.ok) {
          const errorBody = await readJsonSafe(response, null);
          throw Object.assign(
            new Error(formatWorkflowValidationError(errorBody, t("workflows.errors.updateFailed"))),
            { status: response.status, ...errorBody ?? {} }
          );
        }
        return response;
      },
      mutationPayload: { resourceId: definitionId, operation: "update" },
      context: {
        formId: mutationContextId,
        resourceKind: "workflows.definition",
        resourceId: definitionId,
        operation: "update",
        retryLastMutation
      }
    });
    router.push("/backend/definitions");
    router.refresh();
  };
  const handleCustomize = async () => {
    try {
      const result = await runMutation({
        operation: async () => {
          const response = await apiFetch(`/api/workflows/definitions/${definitionId}/customize`, {
            method: "POST"
          });
          if (!response.ok) {
            const errorBody = await readJsonSafe(response, null);
            throw new Error(errorBody?.error || t("workflows.errors.updateFailed"));
          }
          return readJsonSafe(response, null);
        },
        mutationPayload: { resourceId: definitionId, operation: "customize" },
        context: {
          formId: mutationContextId,
          resourceKind: "workflows.definition",
          resourceId: definitionId,
          operation: "customize",
          retryLastMutation
        }
      });
      if (result?.data?.id) {
        router.push(`/backend/definitions/${result.data.id}`);
        router.refresh();
      }
    } catch (error2) {
      const message = error2 instanceof Error ? error2.message : t("workflows.errors.updateFailed");
      flash(message, "error");
    }
  };
  const handleResetToCode = async () => {
    const confirmed = await confirm({
      title: t("workflows.actions.resetToCode"),
      description: t("workflows.actions.resetConfirm"),
      confirmText: t("workflows.actions.resetToCode"),
      variant: "destructive"
    });
    if (!confirmed) return;
    try {
      const result = await runMutation({
        operation: async () => {
          const response = await apiFetch(`/api/workflows/definitions/${definitionId}/reset-to-code`, {
            method: "POST"
          });
          if (!response.ok) {
            const errorBody = await readJsonSafe(response, null);
            throw new Error(errorBody?.error || t("workflows.messages.updateFailed"));
          }
          return readJsonSafe(response, null);
        },
        mutationPayload: { resourceId: definitionId, operation: "reset-to-code" },
        context: {
          formId: mutationContextId,
          resourceKind: "workflows.definition",
          resourceId: definitionId,
          operation: "reset-to-code",
          retryLastMutation
        }
      });
      flash(t("workflows.messages.updated"), "success");
      const codeId = result?.data?.id || `code:${definition?.workflowId}`;
      router.push(`/backend/definitions/${codeId}`);
      router.refresh();
    } catch {
      flash(t("workflows.messages.updateFailed"), "error");
    }
  };
  const fields = React.useMemo(() => createFieldDefinitions(t), [t]);
  const formGroups = React.useMemo(
    () => isMobile ? [] : createFormGroups(t, StepsEditor, TransitionsEditor),
    [t, isMobile]
  );
  const navigateToVisualEditor = React.useCallback(() => {
    router.push(`/backend/definitions/visual-editor?id=${definitionId}`);
  }, [router, definitionId]);
  useSetCurrentRecordInjectionContext(
    buildRecordInjectionContext({
      resourceKind: "workflows.definition",
      resourceId: definitionId ?? null,
      updatedAt: typeof definition?.updatedAt === "string" ? definition.updatedAt : null,
      data: definition ?? null,
      path: pathname
    })
  );
  if (isLoading) {
    return /* @__PURE__ */ jsx(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("workflows.edit.loading") })
    ] }) }) });
  }
  if (isNotFound) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      RecordNotFoundState,
      {
        label: t("workflows.errors.notFound", t("workflows.errors.loadFailed")),
        backHref: "/backend/definitions",
        backLabel: t("workflows.backToList")
      }
    ) }) });
  }
  if (error || !definition) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsxs(PageBody, { children: [
      /* @__PURE__ */ jsx(ErrorMessage, { label: t("workflows.errors.loadFailed") }),
      /* @__PURE__ */ jsx("div", { className: "mt-4 flex justify-center", children: /* @__PURE__ */ jsx(Button, { asChild: true, variant: "outline", children: /* @__PURE__ */ jsx("a", { href: "/backend/definitions", children: t("workflows.backToList") }) }) })
    ] }) });
  }
  if (!initialValues) {
    return null;
  }
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsxs(PageBody, { children: [
      isCodeOnly && /* @__PURE__ */ jsx(Alert, { variant: "info", className: "mb-4", children: /* @__PURE__ */ jsxs(AlertDescription, { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsx("span", { children: t("workflows.source.code.readonlyBanner") }),
        /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: handleCustomize, children: t("workflows.actions.customize") })
      ] }) }),
      isCodeOverride && /* @__PURE__ */ jsx(Alert, { variant: "warning", className: "mb-4", children: /* @__PURE__ */ jsxs(AlertDescription, { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsx("span", { children: t("workflows.source.code_override.banner") }),
        /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: handleResetToCode, children: t("workflows.actions.resetToCode") })
      ] }) }),
      /* @__PURE__ */ jsxs("div", { className: "mb-4 p-4 bg-status-info-bg border border-status-info-border rounded-lg flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3", children: [
          /* @__PURE__ */ jsx("svg", { className: "w-5 h-5 text-status-info-icon", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M13 10V3L4 14h7v7l9-11h-7z" }) }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("p", { className: "text-sm font-medium text-status-info-text", children: t("workflows.edit.visualEditorAvailable") }),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-status-info-text mt-0.5", children: t("workflows.edit.visualEditorDescription") })
          ] })
        ] }),
        /* @__PURE__ */ jsx(Button, { asChild: true, variant: "outline", size: "sm", className: "w-full sm:w-auto border-status-info-border text-status-info-text hover:bg-status-info-bg", children: /* @__PURE__ */ jsx("a", { href: `/backend/definitions/visual-editor?id=${definitionId}`, children: t("workflows.actions.openVisualEditor") }) })
      ] }),
      /* @__PURE__ */ jsx(
        CrudForm,
        {
          title: isCodeOnly ? definition?.workflowName || t("workflows.edit.title") : t("workflows.edit.title"),
          backHref: "/backend/definitions",
          schema: workflowDefinitionFormSchema,
          fields,
          initialValues,
          onSubmit: handleSubmit,
          cancelHref: "/backend/definitions",
          groups: formGroups,
          submitLabel: isCodeOnly ? t("workflows.actions.customize") : t("workflows.form.update"),
          ...isCodeOnly ? { readOnly: true } : {}
        },
        definitionId
      ),
      isMobile && initialValues && /* @__PURE__ */ jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsx(
        MobileDefinitionDetail,
        {
          values: initialValues,
          onEditStep: navigateToVisualEditor,
          onDeleteStep: navigateToVisualEditor,
          onAddStep: navigateToVisualEditor,
          onEditTransition: navigateToVisualEditor,
          onDeleteTransition: navigateToVisualEditor,
          onAddTransition: navigateToVisualEditor
        }
      ) }),
      /* @__PURE__ */ jsx("div", { className: "mt-8", children: /* @__PURE__ */ jsx(
        DefinitionTriggersEditor,
        {
          value: triggers,
          onChange: setTriggers
        }
      ) })
    ] }),
    ConfirmDialogElement
  ] });
}
export {
  EditWorkflowDefinitionPage as default
};
//# sourceMappingURL=page.js.map
