import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { applyMergedDefinition, authModelsSpec, diffDefinition, FeatureUtils, PluginUtils, } from '@baseplate-dev/project-builder-lib';
import { DefinitionDiffAlert, FeatureComboboxFieldController, useBlockUnsavedChangesNavigate, useDefinitionSchema, useProjectDefinition, useResettableForm, } from '@baseplate-dev/project-builder-lib/web';
import { FormActionBar, SectionList, SectionListSection, SectionListSectionContent, SectionListSectionDescription, SectionListSectionHeader, SectionListSectionTitle, SwitchFieldController, } from '@baseplate-dev/ui-components';
import { zodResolver } from '@hookform/resolvers/zod';
import { useMemo } from 'react';
import { useWatch } from 'react-hook-form';
import { createBillingPartialDefinition } from '../schema/models.js';
import { createStripePluginDefinitionSchema } from '../schema/plugin-definition.js';
import { PlanEditorForm } from './plan-editor-form.js';
import '#src/styles.css';
export function StripeDefinitionEditor({ definition: pluginMetadata, metadata, onSave, }) {
    const { definition, definitionContainer, saveDefinitionWithFeedback } = useProjectDefinition();
    const stripePluginDefinitionSchema = useDefinitionSchema(createStripePluginDefinitionSchema);
    const defaultValues = useMemo(() => {
        if (pluginMetadata?.config) {
            return pluginMetadata.config;
        }
        return {
            stripeOptions: {},
            billing: {
                enabled: false,
                featureRef: FeatureUtils.getFeatureIdByNameOrDefault(definition, 'billing'),
                plans: [],
            },
        };
    }, [definition, pluginMetadata?.config]);
    const form = useResettableForm({
        resolver: zodResolver(stripePluginDefinitionSchema),
        defaultValues,
    });
    const { control, reset, handleSubmit } = form;
    const billingEnabled = useWatch({ control, name: 'billing.enabled' });
    const billingFeatureRef = useWatch({
        control,
        name: 'billing.featureRef',
    });
    const authModels = definitionContainer.pluginStore.use(authModelsSpec);
    const userModelName = authModels.getAuthModelsOrThrow(definition).user;
    const billingFeatureName = FeatureUtils.resolveFeatureName(definition, billingFeatureRef);
    const partialDef = useMemo(() => billingFeatureName
        ? createBillingPartialDefinition(billingFeatureName, userModelName)
        : { enums: [], models: [] }, [billingFeatureName, userModelName]);
    const diff = useMemo(() => diffDefinition(definitionContainer.schema, definitionContainer.definition, partialDef), [definitionContainer, partialDef]);
    const onSubmit = handleSubmit((data) => saveDefinitionWithFeedback((draftConfig) => {
        const billingData = { ...data };
        if (billingData.billing.enabled && billingData.billing.featureRef) {
            const featureName = FeatureUtils.resolveFeatureName(draftConfig, billingData.billing.featureRef);
            const updatedPartialDef = createBillingPartialDefinition(featureName, userModelName);
            applyMergedDefinition(definitionContainer, updatedPartialDef)(draftConfig);
            billingData.billing.featureRef =
                FeatureUtils.getFeatureIdByNameOrThrow(draftConfig, featureName);
        }
        else {
            billingData.billing = {
                enabled: false,
                plans: [],
            };
        }
        PluginUtils.setPluginConfig(draftConfig, metadata, billingData, definitionContainer);
    }, {
        successMessage: pluginMetadata
            ? 'Successfully saved Stripe configuration!'
            : 'Successfully enabled Stripe plugin!',
        onSuccess: () => {
            onSave();
        },
    }));
    useBlockUnsavedChangesNavigate({ control, reset, onSubmit });
    return (_jsx("div", { className: "payments:relative payments:flex payments:h-full payments:flex-1 payments:flex-col payments:gap-4 payments:overflow-hidden", children: _jsx("div", { className: "payments:mb-[--action-bar-height] payments:flex payments:flex-1 payments:overflow-y-auto", style: {
                '--action-bar-height': '52px',
            }, children: _jsxs("form", { onSubmit: onSubmit, className: "payments:max-w-6xl payments:flex-1", children: [_jsx("div", { className: "payments:pb-16", children: _jsxs(SectionList, { children: [_jsxs(SectionListSection, { children: [_jsxs(SectionListSectionHeader, { children: [_jsx(SectionListSectionTitle, { children: "Stripe Configuration" }), _jsxs(SectionListSectionDescription, { children: ["Stripe provides payment processing and webhook handling for your backend application. Configure the", ' ', _jsx("code", { children: "STRIPE_SECRET_KEY" }), " environment variable in your project to activate Stripe integration."] })] }), _jsx(SectionListSectionContent, { className: "payments:space-y-6", children: _jsx(SwitchFieldController, { label: "Enable Billing", name: "billing.enabled", control: control, description: "When enabled, generates billing models, webhook handler, and subscription management code." }) })] }), billingEnabled && (_jsxs(_Fragment, { children: [_jsxs(SectionListSection, { children: [_jsxs(SectionListSectionHeader, { children: [_jsx(SectionListSectionTitle, { children: "Billing Configuration" }), _jsx(SectionListSectionDescription, { children: "Configure the feature path and review the models that will be created for billing." })] }), _jsxs(SectionListSectionContent, { className: "payments:space-y-6", children: [_jsx(DefinitionDiffAlert, { diff: diff, upToDateMessage: "All required billing models are already configured correctly." }), _jsx(FeatureComboboxFieldController, { label: "Billing Feature Path", name: "billing.featureRef", control: control, canCreate: true, description: "Feature path where billing module code will be generated" })] })] }), _jsx(PlanEditorForm, { control: control })] }))] }) }), _jsx(FormActionBar, { form: form, allowSaveWithoutDirty: !pluginMetadata || diff.hasChanges })] }) }) }));
}
//# sourceMappingURL=stripe-definition-editor.js.map