"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { memo, useCallback, useMemo, useState } from "react";
import { cn } from "@stigmer/theme";
import { WorkflowExecutionPhaseBadge } from "../WorkflowExecutionPhaseBadge.js";
import { formatDuration, formatMicroUsd, formatTokenCount } from "../format-utils.js";
import { sortExecutionRows, } from "./derive-execution-row.js";
const BIGINT_ZERO = BigInt(0);
const COLUMNS = [
    {
        id: "name",
        header: "Name",
        sortField: "name",
        cell: (row) => (_jsx("span", { className: "font-medium text-foreground truncate max-w-[12rem] inline-block", title: row.name, children: row.name || "\u2014" })),
        defaultVisible: true,
        minWidth: "8rem",
    },
    {
        id: "status",
        header: "Status",
        sortField: "phase",
        cell: (row) => _jsx(WorkflowExecutionPhaseBadge, { phase: row.phase }),
        defaultVisible: true,
        minWidth: "6rem",
    },
    {
        id: "started",
        header: "Started",
        sortField: "startedAt",
        cell: (row) => row.startedAt ? (_jsx("time", { dateTime: row.startedAt.toISOString(), title: row.startedAt.toLocaleString(), children: formatRelativeTime(row.startedAt) })) : ("\u2014"),
        defaultVisible: true,
        minWidth: "6rem",
    },
    {
        id: "duration",
        header: "Duration",
        sortField: "duration",
        cell: (row) => row.durationMs != null ? formatDuration(row.durationMs) : "\u2014",
        defaultVisible: true,
        minWidth: "5rem",
        align: "right",
    },
    {
        id: "cost",
        header: "Cost",
        sortField: "cost",
        cell: (row) => row.costMicros > BIGINT_ZERO
            ? formatMicroUsd(row.costMicros)
            : "\u2014",
        defaultVisible: true,
        minWidth: "4.5rem",
        align: "right",
    },
    {
        id: "tokens",
        header: "Tokens",
        sortField: "tokens",
        cell: (row) => row.totalTokens > BIGINT_ZERO
            ? formatTokenCount(row.totalTokens)
            : "\u2014",
        defaultVisible: false,
        minWidth: "4.5rem",
        align: "right",
    },
    {
        id: "progress",
        header: "Tasks",
        sortField: "tasks",
        cell: (row) => row.taskCount > 0 ? (_jsxs("span", { title: `${row.completedTaskCount} of ${row.taskCount} tasks finished`, children: [row.completedTaskCount, "/", row.taskCount] })) : ("\u2014"),
        defaultVisible: true,
        minWidth: "3.5rem",
        align: "right",
    },
    {
        id: "failedTask",
        header: "Failed / Current",
        sortField: null,
        cell: (row) => {
            const label = row.failedTaskName ?? row.currentTaskName;
            if (!label)
                return "\u2014";
            const isFailed = !!row.failedTaskName;
            return (_jsx("span", { className: cn("truncate max-w-[10rem] inline-block text-xs", isFailed ? "text-destructive" : "text-muted-foreground"), title: label, children: label }));
        },
        defaultVisible: true,
        minWidth: "7rem",
    },
];
// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------
/**
 * Data-dense execution history table with sortable columns, keyboard
 * navigation, and responsive column visibility.
 *
 * Columns are defined statically and use existing formatters from
 * `format-utils.ts` and `WorkflowExecutionPhaseBadge`. Sort state
 * is managed internally with configurable defaults.
 *
 * This component renders only the table. Filtering, pagination, and
 * health metrics are composed by the parent `WorkflowExecutionHistory`.
 *
 * @example
 * ```tsx
 * <ExecutionHistoryTable
 *   rows={derivedRows}
 *   onRowClick={(id) => navigate(`/executions/${id}`)}
 * />
 * ```
 */
export const ExecutionHistoryTable = memo(function ExecutionHistoryTable({ rows, isLoading = false, error, onRowClick, visibleColumns, defaultSortField = "startedAt", defaultSortDirection = "desc", className, }) {
    const [sortField, setSortField] = useState(defaultSortField);
    const [sortDir, setSortDir] = useState(defaultSortDirection);
    const activeColumns = useMemo(() => {
        if (visibleColumns) {
            return COLUMNS.filter((col) => visibleColumns.includes(col.id));
        }
        return COLUMNS.filter((col) => col.defaultVisible);
    }, [visibleColumns]);
    const sortedRows = useMemo(() => sortExecutionRows(rows, sortField, sortDir), [rows, sortField, sortDir]);
    const handleSort = useCallback((field) => {
        if (field === sortField) {
            setSortDir((prev) => (prev === "asc" ? "desc" : "asc"));
        }
        else {
            setSortField(field);
            setSortDir("desc");
        }
    }, [sortField]);
    if (error) {
        return (_jsxs("div", { role: "alert", className: cn("rounded-lg border border-destructive/20 bg-destructive/5 p-6 text-center text-sm text-destructive", className), children: ["Failed to load executions", error.message ? `: ${error.message}` : ""] }));
    }
    if (isLoading) {
        return _jsx(LoadingSkeleton, { columnCount: activeColumns.length, className: className });
    }
    if (rows.length === 0) {
        return (_jsx("div", { className: cn("rounded-lg border border-border p-8 text-center text-sm text-muted-foreground", className), children: "No executions yet" }));
    }
    return (_jsx("div", { className: cn("overflow-x-auto rounded-lg border border-border", className), children: _jsxs("table", { role: "table", "aria-label": "Execution history", className: "w-full border-collapse text-sm", children: [_jsx("thead", { children: _jsx("tr", { className: "border-b border-border bg-[var(--stgm-muted,#f4f4f5)]/50", children: activeColumns.map((col) => {
                            const isSorted = col.sortField === sortField;
                            const ariaSortValue = isSorted
                                ? sortDir === "asc"
                                    ? "ascending"
                                    : "descending"
                                : undefined;
                            return (_jsx("th", { scope: "col", className: cn("px-3 py-2 text-xs font-medium text-muted-foreground whitespace-nowrap", col.align === "right" ? "text-right" : "text-left", col.sortField && "cursor-pointer select-none hover:text-foreground transition-colors"), style: { minWidth: col.minWidth }, "aria-sort": ariaSortValue, onClick: col.sortField ? () => handleSort(col.sortField) : undefined, onKeyDown: col.sortField
                                    ? (e) => {
                                        if (e.key === "Enter" || e.key === " ") {
                                            e.preventDefault();
                                            handleSort(col.sortField);
                                        }
                                    }
                                    : undefined, tabIndex: col.sortField ? 0 : undefined, role: col.sortField ? "columnheader" : undefined, children: _jsxs("span", { className: "inline-flex items-center gap-1", children: [col.header, col.sortField && isSorted && (_jsx(SortIndicator, { direction: sortDir }))] }) }, col.id));
                        }) }) }), _jsx("tbody", { children: sortedRows.map((row) => (_jsx(ExecutionTableRow, { row: row, columns: activeColumns, onRowClick: onRowClick }, row.id))) })] }) }));
});
// ---------------------------------------------------------------------------
// Row component
// ---------------------------------------------------------------------------
const ExecutionTableRow = memo(function ExecutionTableRow({ row, columns, onRowClick, }) {
    const clickable = !!onRowClick;
    return (_jsx("tr", { className: cn("border-b border-border-muted transition-colors", clickable && "cursor-pointer hover:bg-[var(--stgm-accent-hover,#f5f5f5)]"), onClick: clickable ? () => onRowClick(row.id) : undefined, onKeyDown: clickable
            ? (e) => {
                if (e.key === "Enter" || e.key === " ") {
                    e.preventDefault();
                    onRowClick(row.id);
                }
            }
            : undefined, tabIndex: clickable ? 0 : undefined, role: clickable ? "link" : undefined, children: columns.map((col) => (_jsx("td", { className: cn("px-3 py-2.5 text-sm tabular-nums", col.align === "right" ? "text-right" : "text-left"), children: col.cell(row) }, col.id))) }));
});
// ---------------------------------------------------------------------------
// Sort indicator
// ---------------------------------------------------------------------------
function SortIndicator({ direction }) {
    return (_jsx("svg", { width: "10", height: "10", viewBox: "0 0 10 10", fill: "currentColor", "aria-hidden": "true", className: "opacity-60", children: direction === "asc" ? (_jsx("path", { d: "M5 2L8.5 7H1.5L5 2Z" })) : (_jsx("path", { d: "M5 8L1.5 3H8.5L5 8Z" })) }));
}
// ---------------------------------------------------------------------------
// Loading skeleton
// ---------------------------------------------------------------------------
function LoadingSkeleton({ columnCount, className, }) {
    return (_jsx("div", { className: cn("overflow-hidden rounded-lg border border-border", className), children: _jsxs("table", { className: "w-full border-collapse text-sm", "aria-label": "Loading execution history", children: [_jsx("thead", { children: _jsx("tr", { className: "border-b border-border bg-[var(--stgm-muted,#f4f4f5)]/50", children: Array.from({ length: columnCount }, (_, i) => (_jsx("th", { className: "px-3 py-2", children: _jsx("div", { className: "h-3 w-16 animate-pulse rounded bg-muted" }) }, i))) }) }), _jsx("tbody", { children: Array.from({ length: 5 }, (_, rowIdx) => (_jsx("tr", { className: "border-b border-border-muted", children: Array.from({ length: columnCount }, (_, colIdx) => (_jsx("td", { className: "px-3 py-2.5", children: _jsx("div", { className: "h-4 animate-pulse rounded bg-muted", style: { width: `${40 + (colIdx * 12) % 40}%` } }) }, colIdx))) }, rowIdx))) })] }) }));
}
// ---------------------------------------------------------------------------
// Relative time formatter
// ---------------------------------------------------------------------------
function formatRelativeTime(date) {
    const now = Date.now();
    const diff = now - date.getTime();
    if (diff < 0)
        return date.toLocaleString();
    if (diff < 60_000)
        return "just now";
    if (diff < 3_600_000) {
        const mins = Math.floor(diff / 60_000);
        return `${mins}m ago`;
    }
    if (diff < 86_400_000) {
        const hours = Math.floor(diff / 3_600_000);
        return `${hours}h ago`;
    }
    if (diff < 604_800_000) {
        const days = Math.floor(diff / 86_400_000);
        return `${days}d ago`;
    }
    return date.toLocaleDateString();
}
//# sourceMappingURL=ExecutionHistoryTable.js.map