'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/**
 * Form Schema drawer — the right-side panel opened from the Forms list "Schema"
 * action. Three tabs: Fields (versioned schema editor), Embed (public snippets
 * + domain restrictions), Notifications (per-form notification settings).
 *
 * Saving the Fields tab creates a new schema version server-side; existing
 * submissions keep referencing the version they were captured against, so
 * historical entries never break when the schema changes.
 */
import * as Tabs from '@radix-ui/react-tabs';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import { fetchFormSchema, saveFormSchema } from '../../lib/forms-service.js';
import { emitFormsChanged } from '../../lib/forms-events.js';
import { ConfirmDialog } from '../ui/ConfirmDialog.js';
import { Drawer } from './Drawer.js';
import { FieldsPanel } from './FieldsPanel.js';
import { EmbedPanel } from './EmbedPanel.js';
import { NotificationsPanel } from './NotificationsPanel.js';
import { FormsErrorState, FormsLoading, btnPrimary, btnSecondary } from './primitives.js';
const TABS = [
    { id: 'fields', label: 'Fields' },
    { id: 'embed', label: 'Embed' },
    { id: 'notifications', label: 'Notifications' },
];
export function FormSchemaDrawer({ form, open, onOpenChange, onSaved, }) {
    const [tab, setTab] = useState('fields');
    const [fields, setFields] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [dirty, setDirty] = useState(false);
    const [saving, setSaving] = useState(false);
    const [confirmDiscard, setConfirmDiscard] = useState(false);
    const formId = form?.id ?? null;
    const hasSubmissions = (form?.totalEntries ?? 0) > 0;
    useEffect(() => {
        if (!open || !formId)
            return;
        setTab('fields');
        setDirty(false);
        setLoading(true);
        setError(null);
        let active = true;
        fetchFormSchema(formId)
            .then((schema) => {
            if (active)
                setFields(schema.fields);
        })
            .catch((e) => {
            if (active)
                setError(e instanceof Error ? e.message : 'Failed to load schema');
        })
            .finally(() => {
            if (active)
                setLoading(false);
        });
        return () => {
            active = false;
        };
    }, [open, formId]);
    function handleFieldsChange(next) {
        setFields(next);
        setDirty(true);
    }
    async function handleSave() {
        if (!formId)
            return;
        setSaving(true);
        const res = await saveFormSchema(formId, fields.map((f, i) => ({ ...f, sortOrder: i })));
        setSaving(false);
        if (res.error) {
            toast.error(res.error);
            return;
        }
        setDirty(false);
        toast.success('Schema saved.');
        emitFormsChanged();
        onSaved?.();
    }
    function requestClose(next) {
        if (!next && dirty) {
            setConfirmDiscard(true);
            return;
        }
        onOpenChange(next);
    }
    if (!form)
        return null;
    return (_jsxs(_Fragment, { children: [_jsx(Drawer, { open: open, onOpenChange: requestClose, title: form.name, description: `/${form.slug}`, width: "max-w-2xl", footer: tab === 'fields' ? (_jsxs(_Fragment, { children: [_jsx("button", { className: btnSecondary, onClick: () => requestClose(false), children: "Close" }), _jsx("button", { className: btnPrimary, onClick: handleSave, disabled: saving || loading, children: saving ? 'Saving…' : 'Save Schema' })] })) : undefined, children: _jsxs(Tabs.Root, { value: tab, onValueChange: setTab, children: [_jsx(Tabs.List, { className: "border-border mb-4 flex gap-1 border-b", "aria-label": "Form schema sections", children: TABS.map((t) => (_jsx(Tabs.Trigger, { value: t.id, className: "text-muted-foreground hover:text-foreground data-[state=active]:text-foreground data-[state=active]:border-primary focus-visible:ring-ring -mb-px border-b-2 border-transparent px-3 py-2 text-sm font-medium transition-colors focus-visible:ring-2 focus-visible:outline-none", children: t.label }, t.id))) }), _jsx(Tabs.Content, { value: "fields", tabIndex: -1, children: loading ? (_jsx(FormsLoading, { label: "Loading schema\u2026" })) : error ? (_jsx(FormsErrorState, { message: error, onRetry: () => formId && setTab('fields') })) : (_jsx(FieldsPanel, { fields: fields, onChange: handleFieldsChange, hasSubmissions: hasSubmissions })) }), _jsx(Tabs.Content, { value: "embed", tabIndex: -1, children: formId && _jsx(EmbedPanel, { formId: formId, slug: form.slug, status: form.status }) }), _jsx(Tabs.Content, { value: "notifications", tabIndex: -1, children: formId && _jsx(NotificationsPanel, { formId: formId, onChanged: onSaved }) })] }) }), _jsx(ConfirmDialog, { open: confirmDiscard, onClose: () => setConfirmDiscard(false), onConfirm: () => {
                    setDirty(false);
                    onOpenChange(false);
                }, title: "Discard unsaved changes?", description: "You have unsaved schema changes. Closing now will discard them.", confirmLabel: "Discard", cancelLabel: "Keep editing", destructive: true })] }));
}
//# sourceMappingURL=FormSchemaDrawer.js.map