import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useState } from "react";
import { Check } from "lucide-react";
import { useEditContext } from "../client/editContext";
import { Button } from "../../components/ui/button";
import { Popover, PopoverContent, PopoverTrigger, } from "../../components/ui/popover";
import { cn } from "../../lib/utils";
import { getAbsoluteIconUrl } from "../utils";
import { SimpleTable } from "./SimpleTable";
import { Spinner } from "./Spinner";
function getWorkboxItemKey(item) {
    return [
        item.id?.toLowerCase(),
        item.language?.toLowerCase(),
        item.version ?? 0,
        item.database?.toLowerCase() ?? "",
    ].join("|");
}
function getWorkboxItemIdentityKey(item) {
    return [
        item.id?.toLowerCase(),
        item.language?.toLowerCase(),
        item.database?.toLowerCase() ?? "",
    ].join("|");
}
function getValidationErrorLevelClass(level) {
    switch (level) {
        case 0:
            return "text-feedback-green";
        case 1:
            return "text-feedback-blue";
        case 2:
            return "text-feedback-orange";
        case 3:
            return "text-component-shared";
        case 4:
        case 5:
            return "text-feedback-red";
    }
}
/**
 * Presentational table of workbox items shared by the Workbox sidebar and the
 * Publish dialog. Renders the Item / State / Actions / Validation columns,
 * lazily resolves missing item icons, and exposes per-row workflow command
 * buttons. Loading and empty states are handled internally.
 */
export function WorkboxItemsTable({ items, isLoading, emptyMessage, headerNotice, onAfterWorkflowCommand, }) {
    const editContext = useEditContext();
    const [validationOverlayItem, setValidationOverlayItem] = useState();
    const [isValidationOpen, setIsValidationOpen] = useState(false);
    const [iconByItemKey, setIconByItemKey] = useState({});
    const validationResult = editContext?.validationResult;
    useEffect(() => {
        if (!editContext?.itemsRepository || items.length === 0)
            return;
        const descriptorsMissingIcons = items
            .filter((item) => !item.icon && !iconByItemKey[getWorkboxItemKey(item.item)])
            .map((item) => item.item);
        if (descriptorsMissingIcons.length === 0)
            return;
        let cancelled = false;
        const descriptorKeysByIdentity = new Map();
        descriptorsMissingIcons.forEach((descriptor) => {
            const identityKey = getWorkboxItemIdentityKey(descriptor);
            const keys = descriptorKeysByIdentity.get(identityKey) ?? [];
            keys.push(getWorkboxItemKey(descriptor));
            descriptorKeysByIdentity.set(identityKey, keys);
        });
        editContext.itemsRepository
            .getItemsStubs(descriptorsMissingIcons, editContext.currentItemDescriptor)
            .then((stubs) => {
            if (cancelled || stubs.length === 0)
                return;
            setIconByItemKey((current) => {
                const next = { ...current };
                let changed = false;
                stubs.forEach((stub) => {
                    if (!stub.icon)
                        return;
                    next[getWorkboxItemKey(stub)] = stub.icon;
                    changed = true;
                    descriptorKeysByIdentity
                        .get(getWorkboxItemIdentityKey(stub))
                        ?.forEach((key) => {
                        next[key] = stub.icon;
                        changed = true;
                    });
                });
                return changed ? next : current;
            });
        })
            .catch((error) => {
            console.error("Error loading workbox item icons:", error);
        });
        return () => {
            cancelled = true;
        };
    }, [
        editContext?.itemsRepository,
        editContext?.currentItemDescriptor,
        iconByItemKey,
        items,
    ]);
    if (!editContext)
        return null;
    const nameBodyTemplate = (wbItem) => {
        const icon = wbItem.icon || iconByItemKey[getWorkboxItemKey(wbItem.item)];
        return (_jsxs("div", { className: "flex min-w-0 items-start gap-2", children: [icon && (_jsx("img", { src: getAbsoluteIconUrl(icon, 24), alt: "", width: 24, height: 24, className: "h-6 w-6 shrink-0 object-contain" })), _jsxs("div", { className: "min-w-0", children: [_jsxs("div", { className: "break-all", children: [_jsx("span", { className: "font-medium", children: wbItem.name }), " ", _jsxs("span", { className: "text-neutral-grey-50", children: ["(", wbItem.item.language, ", ", wbItem.item.version, ")"] })] }), wbItem.path && (_jsx("div", { className: "text-neutral-grey-50 mt-0.5 text-xs break-all", children: wbItem.path }))] })] }));
    };
    const stateBodyTemplate = (item) => {
        if (item.isPublishable) {
            const targets = Object.keys(item.publishStatus);
            return targets.map((x) => (_jsxs("div", { children: [targets.length > 1 && (_jsxs(_Fragment, { children: [_jsx("b", { children: x }), ":"] })), item.publishStatus[x]] }, x)));
        }
        else
            return item.workflowState;
    };
    const actionsBodyTemplate = (item) => {
        return (_jsx("div", { className: "flex flex-wrap gap-1", children: !item.isFinalState &&
                item.workflowCommands?.map((action) => {
                    return (_jsx(Button, { className: "p-1 text-xs", onClick: async () => {
                            await editContext.operations.executeWorkflowCommand(item.item, action.id);
                            onAfterWorkflowCommand?.();
                        }, size: "sm", children: action.name }, action.id));
                }) }));
    };
    const validationTemplate = (item) => {
        const validator = validationResult?.find((x) => x.item.id === item.item.id &&
            x.item.language === item.item.language &&
            x.item.version === item.item.version);
        if (!validator || !validator.results.length)
            return null;
        const isOpen = isValidationOpen &&
            validationOverlayItem?.item.id === item.item.id &&
            validationOverlayItem?.item.language === item.item.language &&
            validationOverlayItem?.item.version === item.item.version;
        return (_jsxs(Popover, { open: isOpen, onOpenChange: (open) => {
                setIsValidationOpen(open);
                setValidationOverlayItem(open ? item : undefined);
            }, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsx("button", { type: "button", className: cn("hover:bg-neutral-grey-5 inline-flex h-5 min-w-5 items-center justify-center rounded px-1 text-xs", getValidationErrorLevelClass(validator.results.reduce((prev, curr) => Math.max(prev, curr.result), 0))), children: validator.results.length }) }), _jsxs(PopoverContent, { side: "left", align: "start", sideOffset: 8, collisionPadding: 8, className: "w-80 max-w-[calc(100vw-2rem)] overflow-hidden p-0", children: [_jsxs("div", { className: "border-border-default bg-neutral-grey-5 border-b px-3 py-2", children: [_jsx("div", { className: "text-neutral-grey-100 text-xs font-medium", children: "Validation issues" }), _jsxs("div", { className: "text-neutral-grey-50 text-[11px]", children: [validator.results.length, " ", validator.results.length === 1 ? "issue" : "issues", " found"] })] }), _jsx("div", { className: "divide-border-default max-h-[60vh] divide-y overflow-auto", children: validator.results.map((x) => (_jsxs("div", { className: "flex flex-col gap-1 px-3 py-2", children: [_jsxs("div", { className: "flex items-center justify-between gap-2", children: [_jsx("div", { className: "text-neutral-grey-100 truncate text-xs font-medium", title: x.fieldName, children: x.fieldName }), _jsx("span", { className: "bg-neutral-grey-5 text-neutral-grey-50 shrink-0 rounded-sm px-1.5 py-0.5 text-[10px] font-medium", children: x.validator })] }), _jsx("div", { className: cn("text-xs break-words", getValidationErrorLevelClass(x.result)), children: x.message })] }, x.fieldId + x.itemId))) })] })] }));
    };
    const columns = [
        { body: nameBodyTemplate, header: "Item" },
        { body: stateBodyTemplate, header: "State" },
        { body: actionsBodyTemplate, header: "Actions" },
        {
            body: validationTemplate,
            align: "center",
            header: _jsx(Check, { className: "h-4 w-4" }),
        },
    ];
    if (isLoading) {
        return (_jsxs("div", { className: "text-neutral-grey-50 flex h-full items-center justify-center gap-2 text-xs", children: [_jsx(Spinner, { size: "sm" }), " Loading..."] }));
    }
    if (items.length === 0) {
        return (_jsx("div", { className: "text-neutral-grey-50 flex h-full items-center justify-center text-xs", children: emptyMessage }));
    }
    return (_jsxs(_Fragment, { children: [headerNotice, _jsx(SimpleTable, { items: items, columns: columns })] }));
}
//# sourceMappingURL=WorkboxItemsTable.js.map