import { jsx as _jsx } from "react/jsx-runtime";
import { useEffect, useState } from 'react';
import { SelectBox } from '@vertesia/ui/core';
import { useUserSession } from '@vertesia/ui/session';
import { facetOptionNameLabel } from './utils/utils';
export function EnvironmentFacet({ search, buckets, placeholder = "All Environments", className }) {
    const { client } = useUserSession();
    const [options, setOptions] = useState([]);
    const filterValue = search.getFilterValue("environment");
    const onChange = (option) => {
        search.setFilterValue("environment", option?._id);
    };
    useEffect(() => {
        if (client) {
            const options = buckets.map(async (bucket) => {
                let name;
                await client.environments.retrieve(bucket._id).then((environment) => {
                    name = environment.name;
                }).catch(() => {
                    name = `${bucket._id} (deleted)`;
                });
                if (!name) {
                    name = bucket._id;
                }
                return {
                    ...bucket,
                    name
                };
            });
            Promise.all(options).then(resolvedOptions => {
                resolvedOptions.sort((a, b) => a.name.localeCompare(b.name));
                setOptions(resolvedOptions);
            });
        }
    }, [buckets, client]);
    const value = options?.find((option) => option._id === filterValue);
    return (_jsx(SelectBox, { filterBy: "name", className: className, isClearable: true, optionLabel: facetOptionNameLabel, options: options, value: value, onChange: onChange, by: '_id', placeholder: placeholder }));
}
//# sourceMappingURL=EnvironmentFacet.js.map