'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
 * Notifications tab of the Form Schema drawer. Persists per-form notification
 * settings (recipients, reply-to, subject/message templates, field inclusion,
 * autoresponder). Actual email/webhook delivery + the "send test" action are
 * wired in a later phase (PR 6); this panel owns the configuration only.
 */
import { useEffect, useState } from 'react';
import * as Switch from '@radix-ui/react-switch';
import { toast } from 'sonner';
import { fetchNotificationSettings, updateNotificationSettings, } from '../../lib/forms-service.js';
import { emitFormsChanged } from '../../lib/forms-events.js';
import { FormsErrorState, FormsLoading, btnPrimary } from './primitives.js';
const inputCls = 'border-border bg-input-background text-foreground focus-visible:ring-ring w-full rounded-md border px-2.5 py-1.5 text-sm focus-visible:ring-2 focus-visible:outline-none';
export function NotificationsPanel({ formId, onChanged, }) {
    const [settings, setSettings] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [saving, setSaving] = useState(false);
    useEffect(() => {
        let active = true;
        setLoading(true);
        setError(null);
        fetchNotificationSettings(formId)
            .then((s) => {
            if (active)
                setSettings(s);
        })
            .catch((e) => {
            if (active)
                setError(e instanceof Error ? e.message : 'Failed to load notification settings');
        })
            .finally(() => {
            if (active)
                setLoading(false);
        });
        return () => {
            active = false;
        };
    }, [formId]);
    function patch(p) {
        setSettings((cur) => (cur ? { ...cur, ...p } : cur));
    }
    async function save() {
        if (!settings)
            return;
        setSaving(true);
        const res = await updateNotificationSettings(formId, settings);
        setSaving(false);
        if (res.error) {
            toast.error(res.error);
            return;
        }
        if (res.data)
            setSettings(res.data);
        toast.success('Notification settings saved.');
        emitFormsChanged();
        onChanged?.();
    }
    if (loading)
        return _jsx(FormsLoading, { label: "Loading notification settings\u2026" });
    if (error)
        return _jsx(FormsErrorState, { message: error });
    if (!settings)
        return null;
    return (_jsxs("div", { className: "space-y-4", children: [_jsx(ToggleRow, { label: "Enable notifications", help: "Email the recipients below when a new entry arrives.", checked: settings.enabled, onChange: (v) => patch({ enabled: v }) }), _jsxs("fieldset", { disabled: !settings.enabled, className: "space-y-4 transition-opacity disabled:opacity-50", children: [_jsx(Field, { label: "Recipients", hint: "Comma-separated email addresses", children: _jsx("input", { type: "text", value: settings.recipients.join(', '), onChange: (e) => patch({
                                recipients: e.target.value
                                    .split(',')
                                    .map((s) => s.trim())
                                    .filter(Boolean),
                            }), placeholder: "team@example.com", className: inputCls }) }), _jsx(Field, { label: "Reply-to field key", hint: "Field whose value is used as the reply-to address", children: _jsx("input", { type: "text", value: settings.replyToFieldKey ?? '', onChange: (e) => patch({ replyToFieldKey: e.target.value || null }), placeholder: "email", className: inputCls }) }), _jsx(Field, { label: "Subject template", children: _jsx("input", { type: "text", value: settings.subjectTemplate ?? '', onChange: (e) => patch({ subjectTemplate: e.target.value }), placeholder: "New submission from {{name}}", className: inputCls }) }), _jsx(Field, { label: "Message template", children: _jsx("textarea", { rows: 3, value: settings.messageTemplate ?? '', onChange: (e) => patch({ messageTemplate: e.target.value }), className: inputCls }) }), _jsx(ToggleRow, { label: "Include all fields", help: "Append every submitted field to the notification body.", checked: settings.includeFields ?? true, onChange: (v) => patch({ includeFields: v }) }), _jsx(ToggleRow, { label: "Exclude sensitive fields", help: "Omit fields marked as sensitive/PII from the email.", checked: settings.excludeSensitiveFields ?? false, onChange: (v) => patch({ excludeSensitiveFields: v }) }), _jsxs("div", { className: "border-border border-t pt-4", children: [_jsx(ToggleRow, { label: "Auto-response email", help: "Send a confirmation email back to the submitter.", checked: settings.autoresponderEnabled ?? false, onChange: (v) => patch({ autoresponderEnabled: v }) }), settings.autoresponderEnabled && (_jsxs("div", { className: "mt-3 space-y-3", children: [_jsx(Field, { label: "Auto-response subject", children: _jsx("input", { type: "text", value: settings.autoresponderSubject ?? '', onChange: (e) => patch({ autoresponderSubject: e.target.value }), className: inputCls }) }), _jsx(Field, { label: "Auto-response body", children: _jsx("textarea", { rows: 3, value: settings.autoresponderBody ?? '', onChange: (e) => patch({ autoresponderBody: e.target.value }), className: inputCls }) })] }))] })] }), _jsx("p", { className: "text-muted-foreground text-xs", children: "Email & webhook delivery (including the test action) is wired in an upcoming release. Settings saved here apply automatically once delivery is enabled." }), _jsx("div", { className: "flex justify-end", children: _jsx("button", { className: btnPrimary, onClick: save, disabled: saving, children: saving ? 'Saving…' : 'Save notifications' }) })] }));
}
function ToggleRow({ label, help, checked, onChange, }) {
    return (_jsxs("div", { className: "flex items-center justify-between gap-3", children: [_jsxs("span", { className: "min-w-0", children: [_jsx("span", { className: "text-foreground block text-sm font-medium", children: label }), _jsx("span", { className: "text-muted-foreground block text-sm", children: help })] }), _jsx(Switch.Root, { checked: checked, onCheckedChange: onChange, "aria-label": label, className: "bg-destructive data-[state=checked]:bg-success focus-visible:ring-ring relative h-[18px] w-8 shrink-0 rounded-full transition-colors focus-visible:ring-2 focus-visible:outline-none", children: _jsx(Switch.Thumb, { className: "bg-background block h-3.5 w-3.5 translate-x-0.5 rounded-full shadow-sm transition-transform data-[state=checked]:translate-x-[14px]" }) })] }));
}
function Field({ label, hint, children, }) {
    return (_jsxs("label", { className: "block", children: [_jsx("span", { className: "text-foreground mb-1 block text-sm font-medium", children: label }), children, hint && _jsx("span", { className: "text-muted-foreground mt-1 block text-xs", children: hint })] }));
}
//# sourceMappingURL=NotificationsPanel.js.map