import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Button, ErrorBox, Spinner, useIntersectionObserver } from "@vertesia/ui/core";
import { useEffect, useRef, useState } from "react";
import { DocumentsFacetsNav } from "../../../facets";
import { DocumentTable } from "../DocumentTable";
import { useDocumentSearch, useWatchDocumentSearchFacets, useWatchDocumentSearchResult } from "../search/DocumentSearchContext";
import { DocumentSearchProvider } from "../search/DocumentSearchProvider";
import { ContentDispositionButton } from "./ContentDispositionButton";
import { RefreshCw } from "lucide-react";
const layout = [
    { "name": "Name", "field": "properties.title", "type": "string", "fallback": "name" },
    { "name": "Type", "field": "type.name", "type": "string" },
    { "name": "Status", "field": "status", "type": "string" },
    { "name": "Created At", "field": "created_at", "type": "date" }
];
export function SelectDocument({ onChange }) {
    const onRowClick = (selected) => {
        onChange(selected || undefined);
    };
    return (_jsx(DocumentSearchProvider, { children: _jsx(SelectDocumentImpl, { onRowClick: onRowClick }) }));
}
const LAST_DISPLAYED_VIEW = 'vertesia.content_store.lastDisplayedView';
function SelectDocumentImpl({ onRowClick }) {
    const [isReady, setIsReady] = useState(false);
    const [isGridView, setIsGridView] = useState(localStorage.getItem(LAST_DISPLAYED_VIEW) === 'grid');
    const { search, isLoading, error, objects } = useWatchDocumentSearchResult();
    const loadMoreRef = useRef(null);
    useIntersectionObserver(loadMoreRef, () => {
        isReady && search.loadMore(true);
    }, { deps: [isReady] });
    useEffect(() => {
        search.search().then(() => setIsReady(true));
    }, []);
    const facets = useWatchDocumentSearchFacets();
    const facetSearch = useDocumentSearch();
    const handleRefetch = () => {
        setIsReady(false);
        search.search().then(() => setIsReady(true));
    };
    if (error) {
        return _jsx(ErrorBox, { title: "Search failed", children: error.message });
    }
    return (_jsxs("div", { children: [_jsxs("div", { className: "flex justify-between items-center mb-4", children: [_jsx(DocumentsFacetsNav, { facets: facets, search: facetSearch }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Button, { variant: "outline", onClick: handleRefetch, alt: "Refresh", children: _jsx(RefreshCw, { size: 16 }) }), _jsx(ContentDispositionButton, { onUpdate: setIsGridView })] })] }), _jsx(DocumentTable, { objects: objects || [], isLoading: false, layout: layout, onRowClick: onRowClick, isGridView: isGridView }), _jsx("div", { ref: loadMoreRef, className: 'mt-10' }), isLoading && _jsx("div", { className: 'flex justify-center', children: _jsx(Spinner, { size: 'xl' }) })] }));
}
//# sourceMappingURL=SelectDocument.js.map