"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 } from "@open-mercato/ui/backend/DataTable";
import { Button } from "@open-mercato/ui/primitives/button";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { RowActions } from "@open-mercato/ui/backend/RowActions";
import { ErrorMessage } from "@open-mercato/ui/backend/detail";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { apiCall, 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 { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { ListEmptyState } from "@open-mercato/ui/backend/filters/ListEmptyState";
import { Trash2 } from "lucide-react";
const WORKFLOW_ID_MAX_LENGTH = 100;
function buildDuplicateWorkflowId(sourceWorkflowId, attempt) {
  const suffix = attempt === 0 ? "_copy" : `_copy_${attempt + 1}`;
  const maxBaseLength = Math.max(1, WORKFLOW_ID_MAX_LENGTH - suffix.length);
  const base = sourceWorkflowId.slice(0, maxBaseLength);
  return `${base}${suffix}`;
}
function WorkflowDefinitionsListPage() {
  const [page, setPage] = React.useState(1);
  const [pageSize] = React.useState(20);
  const [total, setTotal] = React.useState(0);
  const [totalPages, setTotalPages] = React.useState(1);
  const t = useT();
  const router = useRouter();
  const queryClient = useQueryClient();
  const [filterValues, setFilterValues] = React.useState({});
  const [deleteTarget, setDeleteTarget] = React.useState(null);
  const { data, isLoading, error } = useQuery({
    queryKey: ["workflow-definitions", "list", filterValues, page],
    queryFn: async () => {
      const params = new URLSearchParams();
      const offset = (page - 1) * pageSize;
      params.set("limit", pageSize.toString());
      params.set("offset", offset.toString());
      if (filterValues.enabled !== void 0 && filterValues.enabled !== "") {
        params.set("enabled", filterValues.enabled);
      }
      if (filterValues.workflowId) params.set("workflowId", filterValues.workflowId);
      if (filterValues.search) params.set("search", filterValues.search);
      const result = await apiCall(
        `/api/workflows/definitions?${params.toString()}`
      );
      if (!result.ok) {
        throw new Error("Failed to fetch workflow definitions");
      }
      const response = result.result;
      if (response?.pagination) {
        setTotal(response.pagination.total || 0);
        const calculatedPages = Math.ceil((response.pagination.total || 0) / pageSize);
        setTotalPages(calculatedPages || 1);
      }
      return response?.data || [];
    }
  });
  const handleDelete = (id, workflowName, updatedAt) => {
    setDeleteTarget({ id, name: workflowName, updatedAt });
  };
  const confirmDelete = async () => {
    if (!deleteTarget) return;
    const result = await withScopedApiRequestHeaders(
      buildOptimisticLockHeader(deleteTarget.updatedAt),
      () => apiCall(`/api/workflows/definitions/${deleteTarget.id}`, {
        method: "DELETE"
      })
    );
    if (result.ok) {
      flash(t("workflows.messages.deleted"), "success");
      queryClient.invalidateQueries({ queryKey: ["workflow-definitions"] });
    } else {
      const conflictError = Object.assign(new Error(t("workflows.messages.deleteFailed")), {
        status: result.status,
        ...result.result && typeof result.result === "object" ? result.result : {}
      });
      if (!surfaceRecordConflict(conflictError, t)) {
        flash(t("workflows.messages.deleteFailed"), "error");
      }
    }
    setDeleteTarget(null);
  };
  const handleToggleEnabled = async (id, currentEnabled, updatedAt) => {
    const result = await withScopedApiRequestHeaders(
      buildOptimisticLockHeader(updatedAt),
      () => apiCall(`/api/workflows/definitions/${id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          enabled: !currentEnabled
        })
      })
    );
    if (result.ok) {
      flash(t("workflows.messages.updated"), "success");
      queryClient.invalidateQueries({ queryKey: ["workflow-definitions"] });
    } else {
      const conflictError = Object.assign(new Error(t("workflows.messages.updateFailed")), {
        status: result.status,
        ...result.result && typeof result.result === "object" ? result.result : {}
      });
      if (!surfaceRecordConflict(conflictError, t)) {
        flash(t("workflows.messages.updateFailed"), "error");
      }
    }
  };
  const handleDuplicate = async (definition) => {
    for (let attempt = 0; attempt < 10; attempt += 1) {
      const duplicateWorkflowId = buildDuplicateWorkflowId(definition.workflowId, attempt);
      const result = await apiCall("/api/workflows/definitions", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          workflowId: duplicateWorkflowId,
          workflowName: definition.workflowName,
          description: definition.description,
          version: definition.version,
          definition: definition.definition,
          metadata: definition.metadata,
          enabled: definition.enabled
        })
      });
      if (result.ok) {
        flash(t("workflows.messages.workflowDuplicated"), "success");
        queryClient.invalidateQueries({ queryKey: ["workflow-definitions"] });
        return;
      }
      if (result.status !== 409) {
        break;
      }
    }
    flash(t("workflows.errors.createFailed"), "error");
  };
  const handleFiltersApply = React.useCallback((values) => {
    const next = {};
    Object.entries(values).forEach(([key, value]) => {
      if (value !== void 0 && value !== "") next[key] = value;
    });
    setFilterValues(next);
    setPage(1);
  }, []);
  const handleFiltersClear = React.useCallback(() => {
    setFilterValues({});
    setPage(1);
  }, []);
  const filters = [
    {
      id: "search",
      type: "text",
      label: t("workflows.filters.search"),
      placeholder: t("workflows.filters.searchPlaceholder")
    },
    {
      id: "enabled",
      type: "select",
      label: t("workflows.filters.status"),
      options: [
        { label: t("common.all"), value: "" },
        { label: t("common.enabled"), value: "true" },
        { label: t("common.disabled"), value: "false" }
      ]
    },
    {
      id: "workflowId",
      type: "text",
      label: t("workflows.filters.workflowId"),
      placeholder: t("workflows.filters.workflowIdPlaceholder")
    }
  ];
  const columns = [
    {
      id: "workflowId",
      header: t("workflows.fields.workflowId"),
      accessorKey: "workflowId",
      meta: { truncate: false },
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "font-mono text-sm", children: row.original.workflowId })
    },
    {
      id: "workflowName",
      header: t("workflows.fields.workflowName"),
      accessorKey: "workflowName",
      meta: { truncate: false },
      cell: ({ row }) => /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx("span", { className: "font-medium", children: row.original.workflowName }),
          row.original.source === "code" && /* @__PURE__ */ jsx(Badge, { variant: "secondary", children: t("workflows.source.code") }),
          row.original.source === "code_override" && /* @__PURE__ */ jsx(Badge, { variant: "outline", children: t("workflows.source.code_override") })
        ] }),
        row.original.description && /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground", children: row.original.description }),
        row.original.metadata?.category && /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground mt-0.5", children: row.original.metadata.category })
      ] })
    },
    {
      id: "version",
      header: t("workflows.fields.version"),
      accessorKey: "version",
      meta: { truncate: false },
      cell: ({ row }) => /* @__PURE__ */ jsxs(Badge, { variant: "secondary", className: "font-mono", children: [
        "v",
        row.original.version
      ] })
    },
    {
      id: "enabled",
      header: t("workflows.fields.enabled"),
      accessorKey: "enabled",
      cell: ({ row }) => /* @__PURE__ */ jsx(
        "button",
        {
          onClick: () => handleToggleEnabled(row.original.id, row.original.enabled, row.original.updatedAt),
          className: `inline-flex items-center px-2 py-1 rounded text-xs font-medium cursor-pointer ${row.original.enabled ? "bg-status-success-bg text-status-success-text hover:bg-status-success-border" : "bg-status-neutral-bg text-status-neutral-text hover:bg-status-neutral-border"}`,
          title: t("workflows.actions.toggleEnabled"),
          children: row.original.enabled ? t("common.yes") : t("common.no")
        }
      )
    },
    {
      id: "tags",
      header: t("workflows.fields.tags"),
      cell: ({ row }) => {
        const tags = row.original.metadata?.tags || [];
        if (tags.length === 0) return /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "-" });
        return /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-1", children: [
          tags.slice(0, 2).map((tag, idx) => /* @__PURE__ */ jsx(Badge, { variant: "secondary", children: tag }, idx)),
          tags.length > 2 && /* @__PURE__ */ jsxs(Badge, { variant: "outline", children: [
            "+",
            tags.length - 2
          ] })
        ] });
      }
    },
    {
      id: "createdAt",
      header: t("workflows.fields.createdAt"),
      accessorKey: "createdAt",
      cell: ({ row }) => {
        const date = new Date(row.original.createdAt);
        return /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: date.toLocaleDateString() });
      }
    },
    {
      id: "actions",
      header: "",
      cell: ({ row }) => {
        const isCodeOnly = row.original.source === "code";
        const items = [
          {
            id: "edit",
            label: isCodeOnly ? t("common.view") : t("common.edit"),
            href: `/backend/definitions/${row.original.id}`
          },
          ...!isCodeOnly ? [{
            id: "edit-visual",
            label: t("workflows.actions.editVisually"),
            href: `/backend/definitions/visual-editor?id=${row.original.id}`
          }] : [],
          ...!isCodeOnly ? [{
            id: row.original.enabled ? "disable" : "enable",
            label: row.original.enabled ? t("common.disable") : t("common.enable"),
            onSelect: () => handleToggleEnabled(row.original.id, row.original.enabled, row.original.updatedAt)
          }] : [],
          ...!isCodeOnly ? [{
            id: "duplicate",
            label: t("common.duplicate"),
            onSelect: () => handleDuplicate(row.original)
          }] : [],
          ...!isCodeOnly ? [{
            id: "delete",
            label: t("common.delete"),
            onSelect: () => handleDelete(row.original.id, row.original.workflowName, row.original.updatedAt),
            destructive: true
          }] : []
        ];
        return /* @__PURE__ */ jsx(RowActions, { items });
      }
    }
  ];
  if (error) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      ErrorMessage,
      {
        label: t("workflows.messages.loadFailed"),
        description: error.message,
        action: /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: () => queryClient.invalidateQueries({ queryKey: ["workflow-definitions"] }), children: t("common.retry", "Retry") })
      }
    ) }) });
  }
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsxs(PageBody, { children: [
    /* @__PURE__ */ jsx(
      DataTable,
      {
        title: t("workflows.list.title"),
        actions: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx(Button, { asChild: true, variant: "outline", children: /* @__PURE__ */ jsx(Link, { href: "/backend/definitions/visual-editor", children: t("workflows.actions.createVisual") }) }),
          /* @__PURE__ */ jsx(Button, { asChild: true, children: /* @__PURE__ */ jsx(Link, { href: "/backend/definitions/create", children: t("workflows.actions.create") }) })
        ] }),
        columns,
        data: data || [],
        filters,
        filterValues,
        onFiltersApply: handleFiltersApply,
        onFiltersClear: handleFiltersClear,
        onRowClick: (row) => router.push(`/backend/definitions/visual-editor?id=${row.id}`),
        perspective: {
          tableId: "workflows.definitions.list"
        },
        emptyState: /* @__PURE__ */ jsx(
          ListEmptyState,
          {
            entityName: t("workflows.list.title"),
            createHref: "/backend/definitions/create",
            createLabel: t("workflows.actions.create")
          }
        ),
        pagination: { page, pageSize, total, totalPages, onPageChange: setPage }
      }
    ),
    /* @__PURE__ */ jsx(Dialog, { open: !!deleteTarget, onOpenChange: (open) => !open && setDeleteTarget(null), children: /* @__PURE__ */ jsxs(DialogContent, { className: "sm:max-w-md", children: [
      /* @__PURE__ */ jsxs(DialogHeader, { children: [
        /* @__PURE__ */ jsx(DialogTitle, { children: t("workflows.confirm.deleteTitle") }),
        /* @__PURE__ */ jsx(DialogDescription, { children: t("workflows.confirm.delete", { name: deleteTarget?.name ?? "" }) })
      ] }),
      /* @__PURE__ */ jsxs(DialogFooter, { children: [
        /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: () => setDeleteTarget(null), children: t("common.cancel") }),
        /* @__PURE__ */ jsxs(Button, { variant: "destructive", onClick: confirmDelete, children: [
          /* @__PURE__ */ jsx(Trash2, {}),
          t("common.delete")
        ] })
      ] })
    ] }) })
  ] }) });
}
export {
  WorkflowDefinitionsListPage as default
};
//# sourceMappingURL=page.js.map
