import { jsx as _jsx } from "react/jsx-runtime";
import { useCallback } from "react";
import { ErrorBox, useFetch, VSelectBox } from "@vertesia/ui/core";
import { useUserSession } from "@vertesia/ui/session";
function getLabel(option) {
    return option.name;
}
export function SelectCollection({ onChange, value, disabled = false, placeholder = "Select a collection", filterOut, allowDynamic = true, multiple = false }) {
    const { client } = useUserSession();
    // Handle collection selection
    const handleSelect = useCallback((collection) => {
        if (multiple) {
            // Multiple selection mode
            const selectedCollections = collection;
            if (selectedCollections && selectedCollections.length > 0) {
                const ids = selectedCollections.map(c => c.id);
                onChange(ids, selectedCollections);
            }
            else {
                onChange(undefined);
            }
        }
        else {
            // Single selection mode
            const selectedCollection = collection;
            if (selectedCollection) {
                onChange(selectedCollection.id, selectedCollection);
            }
            else {
                onChange(undefined);
            }
        }
    }, [onChange, multiple]);
    // Fetch collections
    const { data: collections, error } = useFetch(async () => {
        const allCollections = await client.store.collections.search({
            dynamic: allowDynamic ? undefined : false
        });
        // Filter out collections if filterOut is provided
        if (filterOut && filterOut.length > 0) {
            return allCollections.filter(col => !filterOut.includes(col.id));
        }
        return allCollections;
    }, [client, allowDynamic, filterOut]);
    if (error) {
        return _jsx(ErrorBox, { title: "Error", children: error.message || String(error) });
    }
    // Find the selected collection(s) from the value (collection ID(s))
    const selectedCollection = multiple
        ? collections?.filter(col => Array.isArray(value) && value.includes(col.id)) || []
        : collections?.find(col => col.id === value) || null;
    return (multiple ? (_jsx(VSelectBox, { className: "w-full", by: "id", value: selectedCollection, filterBy: "name", options: collections || [], disabled: disabled, optionLabel: (option) => getLabel(option), placeholder: placeholder, onChange: handleSelect, isClearable: true, multiple: multiple })) : (_jsx(VSelectBox, { className: "w-full", by: "id", value: selectedCollection, filterBy: "name", options: collections || [], disabled: disabled, optionLabel: (option) => getLabel(option), placeholder: placeholder, onChange: handleSelect, isClearable: true, multiple: multiple })));
}
//# sourceMappingURL=SelectCollection.js.map