import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useState } from "react";
import { FileText, Link2, RotateCw } from "lucide-react";
import { checkItemReferences } from "./services/editService";
import { useDelayedTrue } from "./hooks/useDelayedTrue";
import { getAbsoluteIconUrl } from "./utils";
import { InternalLink } from "./ui/InternalLink";
import { SimpleIconButton } from "./ui/SimpleIconButton";
import { Spinner } from "./ui/Spinner";
/**
 * Lists the items that reference the given item according to the link
 * database. Rows navigate to the referencing item. Fetches on mount, so
 * mounting it lazily (e.g. as tab content) defers the query until visible.
 */
export function UsedBy({ item }) {
    const [references, setReferences] = useState();
    const [error, setError] = useState(false);
    const [reloadCounter, setReloadCounter] = useState(0);
    const loading = !references && !error;
    const showSpinner = useDelayedTrue(loading, 250);
    useEffect(() => {
        let cancelled = false;
        setReferences(undefined);
        setError(false);
        checkItemReferences([
            {
                id: item.id,
                language: item.language,
                version: item.version,
                database: item.database,
            },
        ])
            .then((result) => {
            if (cancelled)
                return;
            if (result.type === "success" && result.data?.[0])
                setReferences(result.data[0]);
            else
                setError(true);
        })
            .catch(() => {
            if (!cancelled)
                setError(true);
        });
        return () => {
            cancelled = true;
        };
    }, [item.id, item.language, item.version, item.database, reloadCounter]);
    if (error)
        return (_jsxs("div", { className: "text-neutral-grey-50 flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-xs", "data-testid": "used-by-error", children: [_jsx("span", { children: "Could not load the references for this item." }), _jsx("button", { type: "button", className: "font-medium underline hover:no-underline", onClick: () => setReloadCounter((c) => c + 1), children: "Retry" })] }));
    if (loading)
        return (_jsx("div", { className: "flex h-full items-center justify-center", children: showSpinner && _jsx(Spinner, { className: "text-neutral-grey-50" }) }));
    const rows = references.referencingItems;
    const moreCount = references.totalReferenceCount - rows.length;
    if (rows.length === 0)
        return (_jsx("div", { className: "text-neutral-grey-50 flex h-full items-center justify-center p-4 text-center text-xs", "data-testid": "used-by-empty", children: "No other items link to this item." }));
    return (_jsxs("div", { className: "p-3", "data-testid": "used-by-list", children: [_jsxs("div", { className: "mb-2 flex items-center justify-between gap-2", children: [_jsxs("div", { className: "text-neutral-grey-50 flex min-w-0 items-center gap-2 text-xs font-medium", children: [_jsx(Link2, { strokeWidth: 1, className: "h-4 w-4 shrink-0" }), _jsxs("span", { children: ["Referenced by ", references.totalReferenceCount, " item", references.totalReferenceCount !== 1 ? "s" : ""] })] }), _jsx(SimpleIconButton, { icon: _jsx(RotateCw, { className: "h-4 w-4", strokeWidth: 1 }), label: "Refresh references", size: "small", onClick: () => setReloadCounter((c) => c + 1), "data-testid": "used-by-refresh" })] }), _jsxs("div", { className: "space-y-1", children: [rows.map((referrer, index) => (_jsxs("div", { className: "border-border-default flex items-start gap-2 rounded-md border p-2", "data-testid": "used-by-row", children: [referrer.icon ? (_jsx("img", { src: getAbsoluteIconUrl(referrer.icon), alt: "", className: "mt-0.5 h-4 w-4 shrink-0" })) : (_jsx(FileText, { className: "text-neutral-grey-50 mt-0.5 h-4 w-4 shrink-0", strokeWidth: 1 })), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(InternalLink, { item: {
                                                    id: referrer.id,
                                                    language: referrer.language ?? item.language,
                                                    version: 0,
                                                    database: referrer.database ?? item.database,
                                                }, className: "truncate text-sm font-medium", children: referrer.name }), referrer.templateName && (_jsx("span", { className: "text-neutral-grey-50 shrink-0 text-xs", children: referrer.templateName }))] }), _jsx("div", { className: "text-neutral-grey-50 truncate text-xs", title: referrer.path, children: referrer.path }), !!referrer.fieldNames?.length && (_jsxs("div", { className: "text-neutral-grey-50 text-xs", children: ["Field", referrer.fieldNames.length !== 1 ? "s" : "", ":", " ", referrer.fieldNames.join(", ")] }))] })] }, `${referrer.id}-${referrer.language}-${index}`))), moreCount > 0 && (_jsxs("div", { className: "text-neutral-grey-50 py-1 text-xs italic", children: ["... and ", moreCount, " more"] }))] })] }));
}
//# sourceMappingURL=UsedBy.js.map