"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useEffect, useCallback, useMemo } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@open-mercato/ui/primitives/dialog";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { Alert, AlertDescription } from "@open-mercato/ui/primitives/alert";
import { Button } from "@open-mercato/ui/primitives/button";
import { Trash2 } from "lucide-react";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { JsonBuilder } from "@open-mercato/ui/backend/JsonBuilder";
import { FormFieldArrayEditor } from "./fields/FormFieldArrayEditor.js";
import { ActivityArrayEditor } from "./fields/ActivityArrayEditor.js";
import { MappingArrayEditor } from "./fields/MappingArrayEditor.js";
import { WorkflowSelectorField } from "./fields/WorkflowSelectorField.js";
import { StartPreConditionsEditor } from "./fields/StartPreConditionsEditor.js";
import { nodeToFormValues, formValuesToNodeUpdates, isJsonSchemaFormat } from "../lib/nodeFormTransforms.js";
import { sanitizeId } from "../lib/graph-utils.js";
function JsonConfigEditor({ value, setValue, disabled }) {
  return /* @__PURE__ */ jsx(
    JsonBuilder,
    {
      value: value || {},
      onChange: setValue,
      disabled
    }
  );
}
function NodeEditDialogCrudForm({ node, isOpen, onClose, onSave, onDelete }) {
  const [initialValues, setInitialValues] = useState({});
  const [showJsonSchemaWarning, setShowJsonSchemaWarning] = useState(false);
  useEffect(() => {
    if (node && isOpen) {
      const values = nodeToFormValues(node);
      setInitialValues(values);
      setShowJsonSchemaWarning(isJsonSchemaFormat(node));
    }
  }, [node, isOpen]);
  const handleSubmit = useCallback(async (values) => {
    if (!node) return;
    const sanitizedId = sanitizeId(node.id);
    if (sanitizedId !== node.id) {
      if (typeof window !== "undefined") {
        window.alert(
          `\u26A0\uFE0F Step ID was sanitized from "${node.id}" to "${sanitizedId}" to match schema requirements (lowercase letters, numbers, hyphens, and underscores only).`
        );
      }
    }
    try {
      const updates = formValuesToNodeUpdates(values, node);
      onSave(node.id, updates);
      onClose();
    } catch (error) {
      throw error;
    }
  }, [node, onSave, onClose]);
  const handleDelete = useCallback(() => {
    if (!node || !onDelete) return;
    onDelete(node.id);
  }, [node, onDelete]);
  const handleKeyDown = useCallback((e) => {
    if (e.key === "Escape") {
      onClose();
    }
  }, [onClose]);
  const groups = useMemo(() => {
    if (!node) return [];
    if (node.type === "end") {
      return [
        {
          id: "info",
          column: 1,
          bare: true,
          component: () => /* @__PURE__ */ jsx(Alert, { variant: "info", children: /* @__PURE__ */ jsx(AlertDescription, { children: "End nodes cannot be edited. They mark the completion of the workflow." }) })
        }
      ];
    }
    if (node.type === "start") {
      return [
        {
          id: "info",
          column: 1,
          bare: true,
          component: () => /* @__PURE__ */ jsx(Alert, { variant: "info", className: "mb-4", children: /* @__PURE__ */ jsx(AlertDescription, { children: "Start nodes mark the beginning of the workflow. You can define pre-conditions that must pass before the workflow can be started." }) })
        },
        {
          id: "preConditions",
          title: "Pre-Conditions",
          column: 1,
          description: "Business rules that must pass before the workflow can start",
          fields: ["preConditions"]
        }
      ];
    }
    const baseGroups = [
      {
        id: "basic",
        title: "Basic Information",
        column: 1,
        fields: ["stepName", "description", "timeout"]
      }
    ];
    if (node.type === "userTask") {
      return [
        ...baseGroups,
        {
          id: "userTask",
          title: "User Task Configuration",
          column: 1,
          fields: ["assignedTo", "assignedToRoles", "formKey"]
        },
        {
          id: "formFields",
          title: "Form Fields",
          column: 1,
          description: "Define the form structure for this user task",
          fields: ["formFields"]
        },
        {
          id: "advanced",
          title: "Advanced Configuration",
          column: 1,
          description: "Additional JSON configuration (userTaskConfig, retryPolicy, etc.)",
          fields: ["advancedConfig"]
        }
      ];
    }
    if (node.type === "automated") {
      return [
        ...baseGroups,
        {
          id: "automated",
          title: "Automated Task Configuration",
          column: 1,
          fields: ["activityType", "activityId"]
        },
        {
          id: "stepActivities",
          title: "Step Activities",
          column: 1,
          description: "Activities executed as part of this automated step",
          fields: ["stepActivities"]
        },
        {
          id: "advanced",
          title: "Advanced Configuration",
          column: 1,
          description: "Additional JSON configuration (retryPolicy, etc.)",
          fields: ["advancedConfig"]
        }
      ];
    }
    if (node.type === "subWorkflow") {
      return [
        ...baseGroups,
        {
          id: "subWorkflow",
          title: "Sub-Workflow Configuration",
          column: 1,
          fields: ["subWorkflowId", "subWorkflowVersion"]
        },
        {
          id: "mappings",
          title: "Data Mappings",
          column: 1,
          description: "Map data between parent and sub-workflow",
          fields: ["inputMappings", "outputMappings"]
        },
        {
          id: "advanced",
          title: "Advanced Configuration",
          column: 1,
          description: "Additional JSON configuration",
          fields: ["advancedConfig"]
        }
      ];
    }
    if (node.type === "waitForSignal") {
      return [
        ...baseGroups,
        {
          id: "signal",
          title: "Signal Configuration",
          column: 1,
          fields: ["signalName", "signalTimeout"]
        },
        {
          id: "advanced",
          title: "Advanced Configuration",
          column: 1,
          description: "Additional JSON configuration",
          fields: ["advancedConfig"]
        }
      ];
    }
    return [
      ...baseGroups,
      {
        id: "advanced",
        title: "Advanced Configuration",
        column: 1,
        description: "Additional JSON configuration",
        fields: ["advancedConfig"]
      }
    ];
  }, [node]);
  const fields = useMemo(() => [
    // Basic fields
    {
      id: "stepName",
      label: "Step Name",
      type: "text",
      placeholder: "Enter step name",
      required: true,
      description: "Display name for this step"
    },
    {
      id: "description",
      label: "Description",
      type: "textarea",
      placeholder: "Enter step description",
      description: "Optional description of what this step does"
    },
    {
      id: "timeout",
      label: "Timeout",
      type: "text",
      placeholder: "PT30S or 30000",
      description: "ISO 8601 duration (e.g., PT30S) or milliseconds"
    },
    // UserTask fields
    {
      id: "assignedTo",
      label: "Assigned To",
      type: "text",
      placeholder: "user@example.com or userId",
      description: "User email or ID to assign this task to"
    },
    {
      id: "assignedToRoles",
      label: "Assigned To Roles",
      type: "text",
      placeholder: "admin, manager",
      description: "Comma-separated list of roles that can claim this task"
    },
    {
      id: "formKey",
      label: "Form Key",
      type: "text",
      placeholder: "approval_form",
      description: "Optional form key for external form rendering"
    },
    {
      id: "formFields",
      label: "Form Fields",
      type: "custom",
      component: (props) => /* @__PURE__ */ jsx(
        FormFieldArrayEditor,
        {
          ...props,
          value: props.value,
          isJsonSchemaFormat: showJsonSchemaWarning
        }
      )
    },
    // Automated fields
    {
      id: "activityType",
      label: "Activity Type",
      type: "select",
      options: [
        { value: "SEND_EMAIL", label: "Send Email" },
        { value: "CALL_API", label: "Call API" },
        { value: "UPDATE_ENTITY", label: "Update Entity" },
        { value: "EMIT_EVENT", label: "Emit Event" },
        { value: "CALL_WEBHOOK", label: "Call Webhook" },
        { value: "EXECUTE_FUNCTION", label: "Execute Function" },
        { value: "WAIT", label: "Wait" }
      ],
      description: "Type of activity to execute"
    },
    {
      id: "activityId",
      label: "Activity ID",
      type: "text",
      placeholder: "send_welcome_email",
      description: "Unique identifier for this activity"
    },
    {
      id: "stepActivities",
      label: "Step Activities",
      type: "custom",
      component: (props) => /* @__PURE__ */ jsx(ActivityArrayEditor, { ...props, value: props.value })
    },
    // SubWorkflow fields
    {
      id: "subWorkflowId",
      label: "Sub-Workflow",
      type: "custom",
      component: (props) => /* @__PURE__ */ jsx(WorkflowSelectorField, { ...props, value: props.value })
    },
    {
      id: "subWorkflowVersion",
      label: "Version",
      type: "number",
      placeholder: "1",
      description: "Specific version of the sub-workflow to invoke"
    },
    {
      id: "inputMappings",
      label: "Input Mappings",
      type: "custom",
      component: (props) => /* @__PURE__ */ jsx(
        MappingArrayEditor,
        {
          ...props,
          value: props.value,
          label: "Input Mappings",
          description: "Map parent workflow data to sub-workflow input"
        }
      )
    },
    {
      id: "outputMappings",
      label: "Output Mappings",
      type: "custom",
      component: (props) => /* @__PURE__ */ jsx(
        MappingArrayEditor,
        {
          ...props,
          value: props.value,
          label: "Output Mappings",
          description: "Map sub-workflow output back to parent workflow"
        }
      )
    },
    // WaitForSignal fields
    {
      id: "signalName",
      label: "Signal Name",
      type: "text",
      placeholder: "approval_received",
      description: "Name of the signal to wait for"
    },
    {
      id: "signalTimeout",
      label: "Signal Timeout",
      type: "text",
      placeholder: "PT5M",
      description: "How long to wait for the signal (ISO 8601 duration)"
    },
    // Advanced configuration
    {
      id: "advancedConfig",
      label: "Advanced Configuration (JSON)",
      type: "custom",
      description: "Additional JSON configuration merged with the step data",
      component: (props) => /* @__PURE__ */ jsx(JsonConfigEditor, { ...props })
    },
    // Start node pre-conditions
    {
      id: "preConditions",
      label: "Pre-Conditions",
      type: "custom",
      description: "Business rules that must pass before the workflow can start",
      component: (props) => /* @__PURE__ */ jsx(StartPreConditionsEditor, { ...props, value: props.value })
    }
  ], [showJsonSchemaWarning]);
  if (!isOpen || !node) return null;
  const nodeType = node.type || "unknown";
  const nodeTypeLabel = nodeType.charAt(0).toUpperCase() + nodeType.slice(1).replace(/([A-Z])/g, " $1");
  const canDelete = !!onDelete;
  return /* @__PURE__ */ jsx(Dialog, { open: isOpen, onOpenChange: onClose, children: /* @__PURE__ */ jsxs(
    DialogContent,
    {
      className: "sm:max-w-7xl max-h-[90vh] overflow-hidden flex flex-col !p-0 [&_.grid]:!grid-cols-1",
      onKeyDown: handleKeyDown,
      children: [
        /* @__PURE__ */ jsxs(DialogHeader, { className: "flex-shrink-0 p-6 pb-4 border-b border-border/70", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 mb-2", children: [
            /* @__PURE__ */ jsx(DialogTitle, { children: "Edit Step" }),
            /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "text-xs", children: nodeTypeLabel })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
            /* @__PURE__ */ jsx(DialogDescription, { children: "Configure step properties and behavior" }),
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs text-muted-foreground", children: [
              /* @__PURE__ */ jsx("span", { className: "font-medium", children: "ID:" }),
              /* @__PURE__ */ jsx("code", { className: "px-1.5 py-0.5 rounded bg-muted font-mono", children: node.id })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex-1 overflow-y-auto min-h-0 px-6", children: [
          showJsonSchemaWarning && /* @__PURE__ */ jsx(Alert, { variant: "info", className: "mb-4", children: /* @__PURE__ */ jsx(AlertDescription, { className: "text-xs", children: 'This form uses JSON Schema format. Fields have been converted for visual editing. When you save, it will be converted to the simplified format. To preserve the original JSON Schema, edit it in the "Advanced Configuration (JSON)" section.' }) }),
          /* @__PURE__ */ jsx(
            CrudForm,
            {
              fields,
              groups,
              initialValues,
              onSubmit: handleSubmit,
              embedded: true,
              submitLabel: "Save Step",
              extraActions: canDelete ? /* @__PURE__ */ jsxs(
                Button,
                {
                  type: "button",
                  variant: "outline",
                  onClick: handleDelete,
                  className: "text-red-600 border-red-200 hover:bg-red-50",
                  children: [
                    /* @__PURE__ */ jsx(Trash2, { className: "size-4 mr-2" }),
                    "Delete Step"
                  ]
                }
              ) : void 0
            }
          )
        ] })
      ]
    }
  ) });
}
export {
  NodeEditDialogCrudForm
};
//# sourceMappingURL=NodeEditDialogCrudForm.js.map
