"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useRef, useState } from "react";
import { ApiResourceKind } from "@stigmer/protos/ai/stigmer/commons/apiresource/apiresourcekind/api_resource_kind_pb";
import { cn } from "@stigmer/theme";
import { useResourceCollection } from "../hooks/useResourceCollection.js";
import { useResourceFilters } from "../hooks/useResourceFilters.js";
import { useResourceSelection } from "../hooks/useResourceSelection.js";
import { useViewPreference } from "../hooks/useViewPreference.js";
import { ResourceTable } from "./ResourceTable.js";
import { ResourceCards } from "./ResourceCards.js";
import { ResourceList } from "./ResourceList.js";
import { FilterBar } from "./FilterBar.js";
import { ViewSwitcher } from "./ViewSwitcher.js";
import { BulkActionBar } from "./BulkActionBar.js";
import { ResourceInspector } from "./ResourceInspector.js";
import { EmptyState } from "../../empty-state/index.js";
import { ResourceAvatar } from "./ResourceAvatar.js";
import { ScopeToggle } from "../../library/ScopeToggle.js";
// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------
const DEBOUNCE_MS = 300;
/**
 * Full-featured resource collection workbench that composes headless
 * hooks and focused view components into a complete browsing experience.
 *
 * Provides:
 * - Toolbar with search input, filter chips, and view mode switcher
 * - Three view modes: table, cards, and compact list
 * - Row/card selection with bulk action bar
 * - Optional split-panel inspector for item previews
 * - Empty, loading, and error states
 * - Pagination
 *
 * The workbench is the "drop-in" tier of the resource collection
 * architecture. Platform builders who want more control use the
 * individual hooks and view components directly.
 *
 * @example
 * ```tsx
 * <ResourceWorkbench
 *   listFn={(params) => stigmer.agent.list(params)}
 *   org={activeOrg}
 *   columns={agentColumns}
 *   filterDefs={agentFilterDefs}
 *   renderItemAction={(item) => <AgentActionMenu item={item} />}
 *   onItemClick={(item) => navigate(`/agents/${item.slug}`)}
 *   emptyTitle="No agents yet"
 *   emptyDescription="Create an agent to get started."
 * />
 * ```
 */
export function ResourceWorkbench({ listFn, org, columns = [], filterDefs = [], viewModes = ["table", "cards", "list"], defaultViewMode = "table", viewModeStorageKey, renderCard, renderRow, renderItemAction, renderInspector, bulkActions = [], onItemClick, initialFilters, initialSort, initialQuery, scope: controlledScope = "org", onScopeChange, onStateChange, enableSelection = false, getItemId = defaultGetId, emptyIcon, emptyTitle = "No resources found", emptyDescription = "Try adjusting your search or filters.", emptyAction, onRetry, headerAction, searchPlaceholder = "Search\u2026", "aria-label": ariaLabel = "Resource workbench", className, }) {
    // --- View preference ---------------------------------------------------
    const { viewMode, setViewMode } = useViewPreference(viewModeStorageKey, defaultViewMode);
    // --- Filter/sort/query state -------------------------------------------
    const filtersHook = useResourceFilters({
        filterDefs,
        initialFilters,
        initialSort,
        initialQuery,
        onStateChange,
        queryDebounceMs: DEBOUNCE_MS,
    });
    // --- Pagination --------------------------------------------------------
    const [page, setPage] = useState(1);
    const prevQueryRef = useRef(filtersHook.debouncedQuery);
    if (prevQueryRef.current !== filtersHook.debouncedQuery) {
        prevQueryRef.current = filtersHook.debouncedQuery;
        setPage(1);
    }
    // --- Collection data ---------------------------------------------------
    const collection = useResourceCollection({
        listFn: listFn,
        org,
        query: filtersHook.debouncedQuery,
        scope: controlledScope,
        page,
        sort: filtersHook.sort,
        onSortChange: filtersHook.setSort,
        columns: columns,
        enableSelection,
    });
    // --- Selection ---------------------------------------------------------
    const selection = useResourceSelection(collection.items, getItemId);
    // --- Inspector ---------------------------------------------------------
    const [inspectedItem, setInspectedItem] = useState(null);
    const inspectorEnabled = !!renderInspector;
    const handleItemClick = useCallback((item) => {
        if (inspectorEnabled) {
            setInspectedItem(item);
        }
        onItemClick?.(item);
    }, [inspectorEnabled, onItemClick]);
    // --- Content resolution ------------------------------------------------
    const showSkeletons = collection.isLoading && collection.items.length === 0;
    const showError = !!collection.error && !collection.isLoading;
    const showEmpty = !collection.isLoading && !collection.error && collection.items.length === 0;
    const showContent = collection.items.length > 0;
    const showPagination = collection.totalPages > 1;
    // --- Selected IDs as Set for cards/list views --------------------------
    const selectedIdSet = selection.selectedIds;
    return (_jsxs("div", { "aria-label": ariaLabel, className: cn("flex flex-col gap-3", className), children: [_jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsxs("div", { className: "relative flex-1", children: [_jsx(SearchIcon, { className: "pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground-subtle" }), _jsx("input", { type: "text", value: filtersHook.query, onChange: (e) => filtersHook.setQuery(e.target.value), placeholder: searchPlaceholder, "aria-label": searchPlaceholder, className: cn("w-full rounded-md border border-input bg-background py-1.5 pl-8 pr-3 text-sm", "placeholder:text-muted-foreground-subtle", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring") })] }), onScopeChange && (_jsx(ScopeToggle, { value: controlledScope, onChange: onScopeChange })), viewModes.length > 1 && (_jsx(ViewSwitcher, { value: viewMode, onChange: setViewMode, modes: viewModes })), headerAction] }), _jsx(FilterBar, { filters: filtersHook.filters, filterDefs: filterDefs, onRemoveFilter: filtersHook.removeFilter, onClearAll: filtersHook.clearFilters }), _jsxs("div", { className: "flex min-h-0 flex-1", children: [_jsxs("div", { className: cn("min-w-0 flex-1", collection.isRefetching &&
                            "pointer-events-none opacity-60 transition-opacity"), children: [showSkeletons && _jsx(SkeletonPlaceholder, { viewMode: viewMode }), showError && (_jsx(EmptyState, { variant: "error", errorMessage: collection.error.message, action: onRetry
                                    ? { label: "Retry", onClick: onRetry ?? collection.refetch }
                                    : undefined })), showEmpty && (_jsx(EmptyState, { variant: filtersHook.hasActiveFilters || filtersHook.debouncedQuery
                                    ? "zero-results"
                                    : "first-use", icon: emptyIcon, title: filtersHook.hasActiveFilters || filtersHook.debouncedQuery
                                    ? "No results match your filters"
                                    : emptyTitle, description: filtersHook.hasActiveFilters || filtersHook.debouncedQuery
                                    ? "Try adjusting your search or removing some filters."
                                    : emptyDescription, action: filtersHook.hasActiveFilters
                                    ? {
                                        label: "Clear filters",
                                        onClick: filtersHook.clearFilters,
                                    }
                                    : undefined, children: !filtersHook.hasActiveFilters && !filtersHook.debouncedQuery
                                    ? emptyAction
                                    : undefined })), showContent && viewMode === "table" && collection.table && (_jsx(ResourceTable, { table: collection.table, enableSelection: enableSelection, renderRowAction: renderItemAction, onRowClick: handleItemClick })), showContent && viewMode === "cards" && (_jsx(ResourceCards, { items: collection.items, renderCard: renderCard ??
                                    ((item) => _jsx(DefaultCardContent, { item: item })), enableSelection: enableSelection, selectedIds: selectedIdSet, onToggleSelection: selection.toggleItem, getItemId: getItemId, renderCardAction: renderItemAction, onCardClick: handleItemClick })), showContent && viewMode === "list" && (_jsx(ResourceList, { items: collection.items, renderRow: renderRow ??
                                    ((item) => _jsx(DefaultRowContent, { item: item })), enableSelection: enableSelection, selectedIds: selectedIdSet, onToggleSelection: selection.toggleItem, getItemId: getItemId, renderRowAction: renderItemAction, onRowClick: handleItemClick })), showPagination && (_jsx(PaginationBar, { currentPage: collection.currentPage, totalPages: collection.totalPages, totalCount: collection.totalCount, onPageChange: setPage }))] }), inspectorEnabled && (_jsx(ResourceInspector, { open: inspectedItem !== null, onClose: () => setInspectedItem(null), children: inspectedItem && renderInspector(inspectedItem) }))] }), enableSelection && selection.hasSelection && (_jsx(BulkActionBar, { selectedCount: selection.selectedCount, selectedItems: selection.selectedItems, actions: bulkActions, onCancel: selection.clearSelection }))] }));
}
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
function defaultGetId(item) {
    const r = item;
    if (typeof r.id === "string")
        return r.id;
    if (typeof r.slug === "string")
        return r.slug;
    return "";
}
function DefaultCardContent({ item }) {
    const isSkill = item.kind === ApiResourceKind.skill;
    return (_jsxs("div", { className: "flex items-start gap-3", children: [_jsx(ResourceAvatar, { name: item.name || item.slug, slug: item.slug, iconUrl: item.iconUrl || undefined, hidden: isSkill }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("span", { className: "text-sm font-medium text-foreground", children: item.name || item.slug }), item.org && (_jsx("p", { className: "text-xs text-muted-foreground", children: item.org })), item.description && (_jsx("p", { className: "mt-0.5 line-clamp-2 text-xs text-muted-foreground", children: item.description }))] })] }));
}
function DefaultRowContent({ item }) {
    const isSkill = item.kind === ApiResourceKind.skill;
    return (_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(ResourceAvatar, { name: item.name || item.slug, slug: item.slug, iconUrl: item.iconUrl || undefined, hidden: isSkill, size: "sm" }), _jsx("span", { className: "text-sm font-medium text-foreground", children: item.name || item.slug }), item.org && (_jsx("span", { className: "text-xs text-muted-foreground", children: item.org })), item.description && (_jsxs(_Fragment, { children: [_jsx("span", { className: "text-muted-foreground-subtle", "aria-hidden": "true", children: "\u00B7" }), _jsx("span", { className: "truncate text-xs text-muted-foreground", children: item.description })] }))] }));
}
// ---------------------------------------------------------------------------
// Skeleton placeholder
// ---------------------------------------------------------------------------
function SkeletonPlaceholder({ viewMode, }) {
    if (viewMode === "cards") {
        return (_jsx("div", { className: "grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3", "aria-busy": "true", children: Array.from({ length: 6 }, (_, i) => (_jsxs("div", { className: "flex flex-col gap-3 rounded-lg border border-border bg-card p-4", "aria-hidden": "true", children: [_jsx("div", { className: "h-4 w-3/5 animate-pulse rounded bg-muted" }), _jsx("div", { className: "h-3 w-2/5 animate-pulse rounded bg-muted" }), _jsx("div", { className: "h-3 w-full animate-pulse rounded bg-muted" })] }, i))) }));
    }
    return (_jsx("div", { "aria-busy": "true", children: Array.from({ length: 5 }, (_, i) => (_jsxs("div", { className: "flex items-center gap-3 px-3 py-2.5", "aria-hidden": "true", children: [_jsx("div", { className: "h-4 w-4 shrink-0 animate-pulse rounded bg-muted" }), _jsxs("div", { className: "flex-1 space-y-2", children: [_jsx("div", { className: "h-4 animate-pulse rounded bg-muted", style: { width: `${30 + (i * 7) % 25}%` } }), _jsx("div", { className: "h-3 animate-pulse rounded bg-muted", style: { width: `${55 + (i * 5) % 20}%` } })] })] }, i))) }));
}
// ---------------------------------------------------------------------------
// Pagination
// ---------------------------------------------------------------------------
function PaginationBar({ currentPage, totalPages, totalCount, onPageChange, }) {
    const navBtnClass = cn("inline-flex items-center rounded-md p-1.5", "border border-input bg-background text-foreground", "hover:bg-accent hover:text-accent-foreground", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", "disabled:pointer-events-none disabled:opacity-50");
    return (_jsxs("nav", { "aria-label": "Pagination", className: "flex items-center justify-between border-t border-border pt-3", children: [_jsxs("span", { className: "text-xs text-muted-foreground", children: [totalCount.toLocaleString(), " ", totalCount === 1 ? "result" : "results"] }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("button", { type: "button", onClick: () => onPageChange(currentPage - 1), disabled: currentPage <= 1, "aria-label": "Previous page", className: navBtnClass, children: _jsx(ChevronLeftIcon, {}) }), _jsxs("span", { className: "text-xs text-muted-foreground", children: ["Page ", currentPage, " of ", totalPages] }), _jsx("button", { type: "button", onClick: () => onPageChange(currentPage + 1), disabled: currentPage >= totalPages, "aria-label": "Next page", className: navBtnClass, children: _jsx(ChevronRightIcon, {}) })] })] }));
}
// ---------------------------------------------------------------------------
// Icons
// ---------------------------------------------------------------------------
function SearchIcon({ className }) {
    return (_jsxs("svg", { className: className, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [_jsx("circle", { cx: "6.5", cy: "6.5", r: "4.5" }), _jsx("path", { d: "m10 10 4 4" })] }));
}
function ChevronLeftIcon() {
    return (_jsx("svg", { className: "h-3.5 w-3.5", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "m10 3-5 5 5 5" }) }));
}
function ChevronRightIcon() {
    return (_jsx("svg", { className: "h-3.5 w-3.5", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "m6 3 5 5-5 5" }) }));
}
//# sourceMappingURL=ResourceWorkbench.js.map