'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/**
 * Integrations tab of the Form Schema drawer. Manages signed outbound webhooks
 * (Zapier Catch Hook, Make, custom CRM endpoints) and guides editors through
 * the default Zapier → Webhooks by Zapier → Catch Hook setup.
 */
import { Toggle } from '../ui/Toggle.js';
import { ExternalLink, Loader2, Plus, Trash2, Zap } from 'lucide-react';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import { createFormWebhook, deleteFormWebhook, fetchFormWebhooks, testFormWebhook, updateFormWebhook, } from '../../lib/forms-service.js';
import { ConfirmDialog } from '../ui/ConfirmDialog.js';
import { FormsErrorState, FormsLoading, btnPrimary, btnSecondary } from './primitives.js';
const ZAPIER_CATCH_HOOK_DOCS = 'https://zapier.com/apps/webhook/integrations';
const FORMS_INTEGRATIONS_DOCS = 'https://actuatecms.dev/docs/forms-and-integrations';
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 WebhooksPanel({ formId, formSlug }) {
    const [webhooks, setWebhooks] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [url, setUrl] = useState('');
    const [creating, setCreating] = useState(false);
    const [createdSecret, setCreatedSecret] = useState(null);
    const [pendingDelete, setPendingDelete] = useState(null);
    const [testingId, setTestingId] = useState(null);
    async function reload() {
        setLoading(true);
        setError(null);
        try {
            setWebhooks(await fetchFormWebhooks(formId));
        }
        catch (e) {
            setError(e instanceof Error ? e.message : 'Failed to load webhooks');
        }
        finally {
            setLoading(false);
        }
    }
    useEffect(() => {
        let active = true;
        setLoading(true);
        setError(null);
        fetchFormWebhooks(formId)
            .then((rows) => {
            if (active)
                setWebhooks(rows);
        })
            .catch((e) => {
            if (active)
                setError(e instanceof Error ? e.message : 'Failed to load webhooks');
        })
            .finally(() => {
            if (active)
                setLoading(false);
        });
        return () => {
            active = false;
        };
    }, [formId]);
    async function handleCreate(e) {
        e.preventDefault();
        const trimmed = url.trim();
        if (!trimmed) {
            toast.error('Paste your Catch Hook URL first.');
            return;
        }
        setCreating(true);
        const res = await createFormWebhook(formId, {
            url: trimmed,
            events: ['form.submitted'],
            enabled: true,
        });
        setCreating(false);
        if (res.error) {
            toast.error(res.error);
            return;
        }
        if (res.data?.secret)
            setCreatedSecret(res.data.secret);
        setUrl('');
        toast.success('Webhook connected.');
        await reload();
    }
    async function toggleEnabled(webhook, enabled) {
        const res = await updateFormWebhook(formId, webhook.id, { enabled });
        if (res.error) {
            toast.error(res.error);
            return;
        }
        setWebhooks((rows) => rows.map((row) => (row.id === webhook.id ? { ...row, enabled } : row)));
    }
    async function handleTest(webhookId) {
        setTestingId(webhookId);
        const res = await testFormWebhook(formId, webhookId);
        setTestingId(null);
        if (res.error) {
            toast.error(res.error);
            return;
        }
        if (res.data?.ok) {
            toast.success(`Test delivery succeeded (HTTP ${res.data.status}).`);
        }
        else {
            toast.error(res.data?.error || `Test failed (HTTP ${res.data?.status ?? 'unknown'}).`);
        }
        await reload();
    }
    async function confirmDelete() {
        if (!pendingDelete)
            return;
        const res = await deleteFormWebhook(formId, pendingDelete.id);
        setPendingDelete(null);
        if (res.error) {
            toast.error(res.error);
            return;
        }
        toast.success('Webhook removed.');
        await reload();
    }
    if (loading)
        return _jsx(FormsLoading, { label: "Loading integrations\u2026" });
    if (error)
        return _jsx(FormsErrorState, { message: error, onRetry: () => void reload() });
    return (_jsxs("div", { className: "space-y-5", children: [_jsx("section", { className: "border-border bg-muted/40 space-y-3 rounded-lg border p-4", "aria-labelledby": "zapier-helper-title", children: _jsxs("div", { className: "flex items-start gap-3", children: [_jsx("span", { className: "bg-primary/10 text-primary flex h-9 w-9 shrink-0 items-center justify-center rounded-md", children: _jsx(Zap, { size: 18, "aria-hidden": true }) }), _jsxs("div", { className: "min-w-0 space-y-2", children: [_jsx("h3", { id: "zapier-helper-title", className: "text-foreground text-sm font-medium", children: "Connect to Zapier (recommended)" }), _jsxs("ol", { className: "text-muted-foreground list-decimal space-y-1 pl-4 text-sm", children: [_jsxs("li", { children: ["In Zapier, create a Zap with trigger", ' ', _jsx("span", { className: "text-foreground font-medium", children: "Webhooks by Zapier \u2192 Catch Hook" }), "."] }), _jsx("li", { children: "Copy the hook URL Zapier gives you and paste it below." }), _jsxs("li", { children: ["Map fields in your action step \u2014 submission values arrive under", ' ', _jsx("span", { className: "font-mono text-xs", children: "data.email" }), ",", ' ', _jsx("span", { className: "font-mono text-xs", children: "data.name" }), ", etc."] }), _jsxs("li", { children: ["Use event ", _jsx("span", { className: "font-mono text-xs", children: "form.submitted" }), " only (spam hits emit ", _jsx("span", { className: "font-mono text-xs", children: "form.spam_detected" }), " separately)."] })] }), _jsx("p", { className: "text-muted-foreground text-xs", children: "HubSpot, Salesforce, Slack, and Google Sheets work through Zapier actions \u2014 no native Actuate app required for v1." }), _jsxs("div", { className: "flex flex-wrap gap-3 pt-1", children: [_jsxs("a", { href: ZAPIER_CATCH_HOOK_DOCS, target: "_blank", rel: "noopener noreferrer", className: "text-primary inline-flex items-center gap-1 text-sm font-medium hover:underline", children: ["Open Zapier Webhooks", _jsx(ExternalLink, { size: 14, "aria-hidden": true })] }), _jsxs("a", { href: FORMS_INTEGRATIONS_DOCS, target: "_blank", rel: "noopener noreferrer", className: "text-primary inline-flex items-center gap-1 text-sm font-medium hover:underline", children: ["Full integration guide", _jsx(ExternalLink, { size: 14, "aria-hidden": true })] })] })] })] }) }), _jsxs("form", { onSubmit: handleCreate, className: "space-y-3", children: [_jsxs("label", { className: "block", children: [_jsx("span", { className: "text-foreground mb-1 block text-sm font-medium", children: "Webhook URL" }), _jsx("input", { type: "url", value: url, onChange: (e) => setUrl(e.target.value), placeholder: "https://hooks.zapier.com/hooks/catch/\u2026", className: inputCls, autoComplete: "off" }), _jsxs("span", { className: "text-muted-foreground mt-1 block text-xs", children: ["Paste your Catch Hook URL for form ", _jsx("span", { className: "font-mono", children: formSlug }), ". Payloads are HMAC-signed via ", _jsx("span", { className: "font-mono", children: "X-Actuate-Signature" }), "."] })] }), _jsx("button", { type: "submit", className: `${btnPrimary} inline-flex items-center`, disabled: creating, children: creating ? (_jsxs(_Fragment, { children: [_jsx(Loader2, { className: "mr-2 inline h-4 w-4 animate-spin", "aria-hidden": true }), "Connecting\u2026"] })) : (_jsxs(_Fragment, { children: [_jsx(Plus, { className: "mr-1 inline h-4 w-4", "aria-hidden": true }), "Add webhook"] })) })] }), createdSecret && (_jsxs("div", { className: "border-success/30 bg-success/10 text-foreground space-y-2 rounded-md border px-3 py-3 text-sm", role: "status", children: [_jsx("p", { className: "font-medium", children: "Signing secret (shown once)" }), _jsx("p", { className: "text-muted-foreground text-xs", children: "Store this if your CRM verifies HMAC signatures. You cannot retrieve it again after closing this panel." }), _jsx("pre", { className: "border-border bg-background overflow-x-auto rounded border px-2 py-1.5 font-mono text-xs", children: createdSecret }), _jsx("button", { type: "button", className: btnSecondary, onClick: () => setCreatedSecret(null), children: "Dismiss" })] })), webhooks.length === 0 ? (_jsx("p", { className: "text-muted-foreground text-sm", children: "No webhooks yet. Add a Catch Hook URL to send each submission to your CRM." })) : (_jsx("ul", { className: "space-y-3", "aria-label": "Configured webhooks", children: webhooks.map((webhook) => (_jsxs("li", { className: "border-border flex flex-col gap-3 rounded-lg border p-3 sm:flex-row sm:items-center sm:justify-between", children: [_jsxs("div", { className: "min-w-0", children: [_jsx("p", { className: "text-foreground truncate font-mono text-xs", children: webhook.url }), _jsxs("p", { className: "text-muted-foreground mt-1 text-xs", children: ["Events: ", webhook.events.join(', ') || 'form.submitted', webhook.lastDeliveryAt
                                            ? ` · Last delivery: ${webhook.lastDeliveryStatus ?? 'unknown'}`
                                            : ''] })] }), _jsxs("div", { className: "flex shrink-0 flex-wrap items-center gap-2", children: [_jsx(Toggle, { checked: webhook.enabled, onCheckedChange: (v) => void toggleEnabled(webhook, v), "aria-label": `Enable webhook ${webhook.url}`, variant: "enabled" }), _jsx("button", { type: "button", className: btnSecondary, disabled: testingId === webhook.id, onClick: () => void handleTest(webhook.id), children: testingId === webhook.id ? 'Testing…' : 'Send test' }), _jsxs("button", { type: "button", className: "text-destructive hover:bg-destructive/10 focus-visible:ring-ring inline-flex items-center gap-1 rounded-md px-2 py-1.5 text-sm font-medium focus-visible:ring-2 focus-visible:outline-none", "aria-label": "Remove webhook", onClick: () => setPendingDelete(webhook), children: [_jsx(Trash2, { size: 16, "aria-hidden": true }), "Remove"] })] })] }, webhook.id))) })), _jsx(ConfirmDialog, { open: !!pendingDelete, onClose: () => setPendingDelete(null), onConfirm: () => void confirmDelete(), title: "Remove webhook?", description: "New submissions will no longer be sent to this URL. Existing Zapier Zaps are not deleted \u2014 disable them in Zapier if needed.", confirmLabel: "Remove", cancelLabel: "Keep webhook", destructive: true })] }));
}
//# sourceMappingURL=WebhooksPanel.js.map