import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/*
 * Copyright (c) 2023-2025 Datalayer, Inc.
 * Distributed under the terms of the Modified BSD License.
 */
import { useCallback, useEffect } from 'react';
import { Select } from '@primer/react';
import { useCache, useUser } from './../../hooks/index.js';
import { useLayoutStore } from '../../state/index.js';
const NO_ORGANIZATION_SELECTED_VALUE = 'NO_ORGANIZATION_SELECTED_VALUE';
export const OrganizationSelect = () => {
    const user = useUser();
    const { organization, updateLayoutOrganization, updateLayoutSpace } = useLayoutStore();
    const { useRefreshUserOrganizations, useUserOrganizations } = useCache();
    const { mutate: refreshUserOrganizationsMutate } = useRefreshUserOrganizations();
    const { data: organizations = [] } = useUserOrganizations();
    useEffect(() => {
        if (user) {
            refreshUserOrganizationsMutate();
        }
    }, [user, refreshUserOrganizationsMutate]);
    const onSelectionChange = useCallback((event) => {
        const selectedOrganization = event.target.value;
        const org = selectedOrganization === NO_ORGANIZATION_SELECTED_VALUE
            ? undefined
            : organizations[parseInt(selectedOrganization, 10)];
        updateLayoutOrganization(org);
        updateLayoutSpace(undefined);
    }, [organizations, updateLayoutOrganization, updateLayoutSpace]);
    return (_jsx(_Fragment, { children: _jsxs(Select, { block: true, width: "medium", onChange: onSelectionChange, children: [_jsx(Select.Option, { value: NO_ORGANIZATION_SELECTED_VALUE, selected: organization === undefined, children: "Please select an organization..." }), organizations.map((org, index) => (_jsx(Select.Option, { value: `${index}`, selected: org.id === organization?.id, children: org.name }, org.id)))] }) }));
};
export default OrganizationSelect;
