import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { applyMergedDefinition, diffDefinition, PluginUtils, } from '@baseplate-dev/project-builder-lib';
import { DefinitionDiffAlert, useBlockUnsavedChangesNavigate, useDefinitionSchema, useProjectDefinition, useResettableForm, } from '@baseplate-dev/project-builder-lib/web';
import { FormActionBar, MultiComboboxFieldController, SectionList, SectionListSection, SectionListSectionContent, SectionListSectionDescription, SectionListSectionHeader, SectionListSectionTitle, } from '@baseplate-dev/ui-components';
import { zodResolver } from '@hookform/resolvers/zod';
import { useMemo } from 'react';
import { getAuthPluginDefinition } from '#src/auth/utils/get-auth-plugin-definition.js';
import { AuthConfigTabs } from '#src/common/components/auth-config-tabs.js';
import { createLocalAuthPartialDefinition } from '../schema/models.js';
import { createLocalAuthPluginDefinitionSchema } from '../schema/plugin-definition.js';
import '#src/styles.css';
export function LocalAuthDefinitionEditor({ definition: pluginMetadata, metadata, onSave, }) {
    const { definition, definitionContainer, saveDefinitionWithFeedback } = useProjectDefinition();
    const authPluginDefinitionSchema = useDefinitionSchema(createLocalAuthPluginDefinitionSchema);
    const authDefinition = getAuthPluginDefinition(definition);
    const roles = authDefinition.roles
        .filter((role) => !role.builtIn)
        .map((role) => ({
        label: role.name,
        value: role.id,
    }));
    const defaultValues = useMemo(() => {
        if (pluginMetadata?.config) {
            return pluginMetadata.config;
        }
        return {
            initialUserRoles: [],
            userAdminRoles: [],
        };
    }, [pluginMetadata?.config]);
    const form = useResettableForm({
        resolver: zodResolver(authPluginDefinitionSchema),
        defaultValues,
    });
    const { control, reset, handleSubmit } = form;
    const authFeature = definition.features.find((f) => f.id === authDefinition.authFeatureRef);
    if (!authFeature) {
        throw new Error(`Auth feature not found for ref: ${authDefinition.authFeatureRef}`);
    }
    const partialDef = useMemo(() => createLocalAuthPartialDefinition(authFeature.name), [authFeature.name]);
    const diff = useMemo(() => diffDefinition(definitionContainer.schema, definitionContainer.definition, partialDef), [definitionContainer, partialDef]);
    const onSubmit = handleSubmit((data) => saveDefinitionWithFeedback((draftConfig) => {
        const updatedData = {
            ...data,
        };
        applyMergedDefinition(definitionContainer, partialDef)(draftConfig);
        PluginUtils.setPluginConfig(draftConfig, metadata, updatedData, definitionContainer);
    }, {
        successMessage: 'Successfully saved auth plugin!',
        onSuccess: () => {
            onSave();
        },
    }));
    useBlockUnsavedChangesNavigate({ control, reset, onSubmit });
    return (_jsxs("div", { className: "auth:relative auth:flex auth:h-full auth:flex-1 auth:flex-col auth:gap-4 auth:overflow-hidden", children: [_jsx(AuthConfigTabs, {}), _jsx("div", { className: "auth:mb-[--action-bar-height] auth:flex auth:flex-1 auth:overflow-y-auto", style: {
                    '--action-bar-height': '52px',
                }, children: _jsxs("form", { onSubmit: onSubmit, className: "auth:max-w-6xl auth:flex-1", children: [_jsx("div", { className: "auth:pb-16", children: _jsxs(SectionList, { children: [_jsxs(SectionListSection, { children: [_jsxs(SectionListSectionHeader, { children: [_jsx(SectionListSectionTitle, { children: "Local Auth User Models" }), _jsx(SectionListSectionDescription, { children: "The plugin will automatically configure the models it needs." })] }), _jsx(SectionListSectionContent, { className: "auth:space-y-6", children: _jsx(DefinitionDiffAlert, { diff: diff, upToDateMessage: "All required models are already configured correctly. No changes needed." }) })] }), _jsxs(SectionListSection, { children: [_jsxs(SectionListSectionHeader, { children: [_jsx(SectionListSectionTitle, { children: "Initial User Setup" }), _jsx(SectionListSectionDescription, { children: "In order to access the admin panel, an initial user must be created. To make it easier, the plugin will automatically add a seed script to create the initial user provided a .seed.env exists with the INTIIAL_USER_EMAIL and INTIIAL_USER_PASSWORD variables." })] }), _jsx(SectionListSectionContent, { className: "auth:space-y-6", children: _jsx(MultiComboboxFieldController, { label: "Initial User Roles", name: "initialUserRoles", control: control, options: roles, description: "The roles that will be assigned to the initial user." }) })] }), _jsxs(SectionListSection, { children: [_jsxs(SectionListSectionHeader, { children: [_jsx(SectionListSectionTitle, { children: "User Management Permissions" }), _jsx(SectionListSectionDescription, { children: "Configure which roles can manage users and assign roles to other users in the admin interface." })] }), _jsx(SectionListSectionContent, { className: "auth:space-y-6", children: _jsx(MultiComboboxFieldController, { label: "User Admin Roles", name: "userAdminRoles", control: control, options: roles, description: "Roles that can manage users and assign roles to other users." }) })] })] }) }), _jsx(FormActionBar, { form: form, allowSaveWithoutDirty: !pluginMetadata || diff.hasChanges })] }) })] }));
}
//# sourceMappingURL=local-auth-definition-editor.js.map