import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
import { SelectBox, useFetch } from "@vertesia/ui/core";
import { LastSelectedAccountId_KEY, LastSelectedProjectId_KEY, useUserSession } from "@vertesia/ui/session";
import { useState } from "react";
export function AppProjectSelector({ app, onChange, placeholder }) {
    const { client, project } = useUserSession();
    const { data: projects, error } = useFetch(() => {
        return client.apps.getAppInstallationProjects(app);
    }, [app.id, app.name]);
    const _onChange = (project) => {
        if (onChange) {
            if (!onChange(project)) {
                // if onChange returns true then the defualt on change is called
                return;
            }
        }
        // default on change
        localStorage.setItem(LastSelectedAccountId_KEY, project.account);
        localStorage.setItem(LastSelectedProjectId_KEY + '-' + project.account, project.id);
        window.location.reload();
    };
    if (error) {
        return _jsxs("span", { className: 'text-red-600', children: ["Error: failed to fetch projects: ", error.message] });
    }
    return _jsx(SelectProject, { placeholder: placeholder, initialValue: project?.id, projects: projects || [], onChange: _onChange });
}
function SelectProject({ initialValue, projects, onChange, placeholder = "Select Project" }) {
    const [value, setValue] = useState();
    const _onChange = (value) => {
        setValue(value);
        onChange(value);
    };
    let actualValue = !value && initialValue ? projects.find(p => p.id === initialValue) : value;
    return (_jsx(SelectBox, { by: "id", value: actualValue, options: projects, optionLabel: (option) => option.name, placeholder: placeholder, onChange: _onChange }));
}
//# sourceMappingURL=AppProjectSelector.js.map