import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { createAndApplyModelMergerResults, createModelMergerResults, doesModelMergerResultsHaveChanges, FeatureUtils, ModelUtils, PluginUtils, } from '@baseplate-dev/project-builder-lib';
import { FeatureComboboxFieldController, ModelComboboxFieldController, ModelMergerResultAlert, useBlockUnsavedChangesNavigate, useDefinitionSchema, useProjectDefinition, useResettableForm, } from '@baseplate-dev/project-builder-lib/web';
import { FormActionBar, SectionList, SectionListSection, SectionListSectionContent, SectionListSectionDescription, SectionListSectionHeader, SectionListSectionTitle, } from '@baseplate-dev/ui-components';
import { zodResolver } from '@hookform/resolvers/zod';
import { useMemo } from 'react';
import { createStorageModels } from '../schema/models.js';
import { createStoragePluginDefinitionSchema } from '../schema/plugin-definition.js';
import AdapterEditorForm from './adapter-editor-form.js';
export function StorageDefinitionEditor({ definition: pluginMetadata, metadata, onSave, }) {
    const { definition, definitionContainer, saveDefinitionWithFeedback } = useProjectDefinition();
    const storagePluginDefinitionSchema = useDefinitionSchema(createStoragePluginDefinitionSchema);
    const defaultValues = useMemo(() => {
        if (pluginMetadata?.config) {
            return pluginMetadata.config;
        }
        return {
            modelRefs: {
                file: ModelUtils.getModelIdByNameOrDefault(definition, 'File'),
            },
            storageFeatureRef: FeatureUtils.getFeatureIdByNameOrDefault(definition, 'storage'),
            s3Adapters: [],
        };
    }, [definition, pluginMetadata?.config]);
    const form = useResettableForm({
        resolver: zodResolver(storagePluginDefinitionSchema),
        defaultValues,
    });
    const { control, reset, handleSubmit, watch } = form;
    const modelRefs = watch('modelRefs');
    const storageFeatureRef = watch('storageFeatureRef');
    const pendingModelChanges = useMemo(() => {
        const desiredModels = createStorageModels({ storageFeatureRef }, definitionContainer);
        return createModelMergerResults(modelRefs, desiredModels, definitionContainer);
    }, [definitionContainer, storageFeatureRef, modelRefs]);
    const onSubmit = handleSubmit((data) => saveDefinitionWithFeedback((draftConfig) => {
        const featureRef = FeatureUtils.ensureFeatureByNameRecursively(draftConfig, data.storageFeatureRef);
        const updatedData = {
            ...data,
            storageFeatureRef: featureRef,
        };
        createAndApplyModelMergerResults(draftConfig, updatedData.modelRefs, createStorageModels(updatedData, definitionContainer), definitionContainer);
        PluginUtils.setPluginConfig(draftConfig, metadata, data, definitionContainer.pluginStore);
    }, {
        successMessage: pluginMetadata
            ? 'Successfully saved storage plugin!'
            : 'Successfully enabled storage plugin!',
        onSuccess: () => {
            onSave();
        },
    }));
    useBlockUnsavedChangesNavigate({ control, reset, onSubmit });
    return (_jsxs("form", { onSubmit: onSubmit, className: "storage:mb-[--action-bar-height] storage:max-w-6xl", children: [_jsx("div", { className: "storage:pb-16", children: _jsxs(SectionList, { children: [_jsxs(SectionListSection, { children: [_jsxs(SectionListSectionHeader, { children: [_jsx(SectionListSectionTitle, { children: "Storage Configuration" }), _jsx(SectionListSectionDescription, { children: "Configure your storage settings, file models, and S3 adapters." })] }), _jsxs(SectionListSectionContent, { className: "storage:space-y-6", children: [_jsx(ModelMergerResultAlert, { pendingModelChanges: pendingModelChanges }), _jsxs("div", { className: "storage:grid storage:grid-cols-1 storage:gap-6 storage:md:grid-cols-2", children: [_jsx(ModelComboboxFieldController, { label: "File Model", name: "modelRefs.file", control: control, canCreate: true, description: "The model to use for file storage" }), _jsx(FeatureComboboxFieldController, { label: "Storage Feature Path", name: "storageFeatureRef", control: control, canCreate: true, description: "Specify the feature path where storage endpoints will be generated" })] })] })] }), _jsx(AdapterEditorForm, { control: control })] }) }), _jsx(FormActionBar, { form: form, allowSaveWithoutDirty: !pluginMetadata ||
                    doesModelMergerResultsHaveChanges(pendingModelChanges) })] }));
}
//# sourceMappingURL=storage-definition-editor.js.map