'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useCallback, useEffect } from 'react';
import { Save, ArrowLeft, Plus, Trash2, GripVertical, MessageSquare, ExternalLink, BarChart3, ChevronDown, ChevronRight, Loader2, } from 'lucide-react';
import { useApiData } from '../lib/useApiData.js';
import { cmsApi } from '../lib/api.js';
const FIELD_TYPES = [
    { value: 'text', label: 'Text' },
    { value: 'email', label: 'Email' },
    { value: 'tel', label: 'Phone' },
    { value: 'textarea', label: 'Textarea' },
    { value: 'select', label: 'Dropdown' },
    { value: 'checkbox', label: 'Checkbox' },
    { value: 'number', label: 'Number' },
    { value: 'date', label: 'Date' },
    { value: 'url', label: 'URL' },
    { value: 'file', label: 'File Upload' },
    { value: 'hidden', label: 'Hidden' },
];
export function FormEditor({ formId, onNavigate }) {
    const isNew = !formId;
    const { data: existingForm, loading } = useApiData(formId ? `/collections/forms/${formId}` : null);
    const [name, setName] = useState('');
    const [description, setDescription] = useState('');
    const [status, setStatus] = useState('active');
    const [fields, setFields] = useState([]);
    const [saving, setSaving] = useState(false);
    const [expandedSection, setExpandedSection] = useState('fields');
    const [confirmation, setConfirmation] = useState({
        type: 'message',
        message: 'Thank you! Your submission has been received.',
        redirectUrl: '',
        redirectDelay: 0,
    });
    const [analytics, setAnalytics] = useState({
        enabled: false,
        measurementId: '',
        submitEventName: 'form_submit',
        startEventName: 'form_start',
        trackAsConversion: false,
        conversionValue: 0,
        conversionCurrency: 'USD',
        customParameters: {},
    });
    useEffect(() => {
        if (existingForm) {
            const d = existingForm.data ?? existingForm;
            setName(d.name ?? '');
            setDescription(d.description ?? '');
            setStatus(d.status ?? 'active');
            if (Array.isArray(d.fields))
                setFields(d.fields);
            if (d.confirmation) {
                setConfirmation((prev) => ({ ...prev, ...d.confirmation }));
            }
            if (d.analytics) {
                setAnalytics((prev) => ({ ...prev, ...d.analytics }));
            }
        }
    }, [existingForm]);
    const addField = useCallback((type) => {
        setFields((prev) => [
            ...prev,
            {
                id: crypto.randomUUID(),
                type,
                label: `New ${type} field`,
                required: false,
            },
        ]);
    }, []);
    const removeField = useCallback((id) => {
        setFields((prev) => prev.filter((f) => f.id !== id));
    }, []);
    const updateField = useCallback((id, updates) => {
        setFields((prev) => prev.map((f) => (f.id === id ? { ...f, ...updates } : f)));
    }, []);
    const moveField = useCallback((from, to) => {
        setFields((prev) => {
            const next = [...prev];
            const [moved] = next.splice(from, 1);
            next.splice(to, 0, moved);
            return next;
        });
    }, []);
    const handleSave = async () => {
        setSaving(true);
        try {
            const payload = {
                name,
                description,
                status,
                fields,
                confirmation,
                analytics: analytics.enabled ? analytics : { enabled: false },
            };
            if (isNew) {
                await cmsApi('/collections/forms', {
                    method: 'POST',
                    body: JSON.stringify(payload),
                });
            }
            else {
                await cmsApi(`/collections/forms/${formId}`, {
                    method: 'PUT',
                    body: JSON.stringify(payload),
                });
            }
            onNavigate?.('/forms');
        }
        finally {
            setSaving(false);
        }
    };
    const toggleSection = (section) => {
        setExpandedSection(expandedSection === section ? null : section);
    };
    if (loading) {
        return (_jsx("div", { className: "flex h-64 items-center justify-center p-4", children: _jsx(Loader2, { className: "text-primary h-6 w-6 animate-spin" }) }));
    }
    return (_jsxs("div", { className: "max-w-4xl p-3 pr-6 sm:p-4 sm:pr-8", children: [_jsxs("div", { className: "mb-6 flex items-center gap-3", children: [_jsx("button", { onClick: () => onNavigate?.('/forms'), className: "hover:bg-muted rounded-lg p-2 transition-colors", children: _jsx(ArrowLeft, { className: "text-muted-foreground h-5 w-5" }) }), _jsx("div", { className: "flex-1", children: _jsx("h1", { className: "text-foreground text-xl font-medium", children: isNew ? 'New Form' : 'Edit Form' }) }), _jsxs("button", { onClick: handleSave, disabled: saving || !name.trim(), className: "bg-primary text-primary-foreground hover:bg-primary/90 flex items-center gap-2 rounded-lg px-4 py-2 text-sm transition-colors disabled:opacity-50", children: [saving ? _jsx(Loader2, { className: "h-4 w-4 animate-spin" }) : _jsx(Save, { className: "h-4 w-4" }), saving ? 'Saving...' : 'Save'] })] }), _jsx("div", { className: "border-border bg-card mb-4 rounded-lg border p-4", children: _jsxs("div", { className: "grid gap-4", children: [_jsxs("div", { children: [_jsx("label", { className: "text-foreground mb-1 block text-sm font-medium", children: "Form Name" }), _jsx("input", { type: "text", value: name, onChange: (e) => setName(e.target.value), placeholder: "e.g. Contact Form", className: "border-border focus-visible:ring-ring/50 w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none" })] }), _jsxs("div", { children: [_jsx("label", { className: "text-foreground mb-1 block text-sm font-medium", children: "Description" }), _jsx("input", { type: "text", value: description, onChange: (e) => setDescription(e.target.value), placeholder: "Brief description of this form", className: "border-border focus-visible:ring-ring/50 w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none" })] }), _jsxs("div", { children: [_jsx("label", { className: "text-foreground mb-1 block text-sm font-medium", children: "Status" }), _jsxs("select", { value: status, onChange: (e) => setStatus(e.target.value), className: "border-border focus-visible:ring-ring/50 rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none", children: [_jsx("option", { value: "active", children: "Active" }), _jsx("option", { value: "inactive", children: "Inactive" })] })] })] }) }), _jsxs("div", { className: "border-border bg-card mb-4 rounded-lg border", children: [_jsx("button", { onClick: () => toggleSection('fields'), className: "hover:bg-muted flex w-full items-center justify-between p-4 transition-colors", children: _jsxs("div", { className: "flex items-center gap-2", children: [expandedSection === 'fields' ? (_jsx(ChevronDown, { className: "h-4 w-4" })) : (_jsx(ChevronRight, { className: "h-4 w-4" })), _jsx("span", { className: "text-foreground font-medium", children: "Form Fields" }), _jsxs("span", { className: "text-muted-foreground text-sm", children: ["(", fields.length, ")"] })] }) }), expandedSection === 'fields' && (_jsxs("div", { className: "border-border border-t p-4", children: [_jsx("div", { className: "mb-4 flex flex-wrap gap-2", children: FIELD_TYPES.map((ft) => (_jsxs("button", { onClick: () => addField(ft.value), className: "border-border hover:bg-muted flex items-center gap-1 rounded-lg border px-3 py-1.5 text-xs transition-colors", children: [_jsx(Plus, { className: "h-3 w-3" }), " ", ft.label] }, ft.value))) }), fields.length === 0 ? (_jsx("p", { className: "text-muted-foreground py-6 text-center text-sm", children: "Click a field type above to add it to your form." })) : (_jsx("div", { className: "flex flex-col gap-2", children: fields.map((field, index) => (_jsxs("div", { draggable: true, onDragStart: (e) => e.dataTransfer.setData('text/plain', String(index)), onDragOver: (e) => e.preventDefault(), onDrop: (e) => {
                                        const from = Number(e.dataTransfer.getData('text/plain'));
                                        moveField(from, index);
                                    }, className: "border-border bg-muted hover:bg-card flex items-center gap-3 rounded-lg border p-3 transition-colors", children: [_jsx(GripVertical, { className: "text-muted-foreground h-4 w-4 shrink-0 cursor-grab" }), _jsx("input", { type: "text", value: field.label, onChange: (e) => updateField(field.id, { label: e.target.value }), className: "border-border focus-visible:ring-ring/50 flex-1 rounded border px-2 py-1 text-sm focus:ring-1 focus:outline-none" }), _jsx("span", { className: "bg-muted text-muted-foreground shrink-0 rounded px-2 py-0.5 text-xs", children: field.type }), _jsxs("label", { className: "text-muted-foreground flex shrink-0 items-center gap-1 text-xs", children: [_jsx("input", { type: "checkbox", checked: field.required, onChange: (e) => updateField(field.id, { required: e.target.checked }), className: "rounded" }), "Required"] }), _jsx("button", { onClick: () => removeField(field.id), className: "text-destructive hover:bg-destructive/10 shrink-0 rounded p-1 transition-colors", children: _jsx(Trash2, { className: "h-4 w-4" }) })] }, field.id))) }))] }))] }), _jsxs("div", { className: "border-border bg-card mb-4 rounded-lg border", children: [_jsx("button", { onClick: () => toggleSection('confirmation'), className: "hover:bg-muted flex w-full items-center justify-between p-4 transition-colors", children: _jsxs("div", { className: "flex items-center gap-2", children: [expandedSection === 'confirmation' ? (_jsx(ChevronDown, { className: "h-4 w-4" })) : (_jsx(ChevronRight, { className: "h-4 w-4" })), _jsx(MessageSquare, { className: "text-success h-4 w-4" }), _jsx("span", { className: "text-foreground font-medium", children: "Confirmation" }), _jsx("span", { className: "bg-muted text-muted-foreground rounded px-2 py-0.5 text-xs", children: confirmation.type === 'message' ? 'Show Message' : 'Redirect' })] }) }), expandedSection === 'confirmation' && (_jsxs("div", { className: "border-border border-t p-4", children: [_jsxs("div", { className: "mb-4", children: [_jsx("label", { className: "text-foreground mb-2 block text-sm font-medium", children: "After submission" }), _jsxs("div", { className: "flex gap-3", children: [_jsxs("label", { className: "hover:bg-muted flex cursor-pointer items-center gap-2 rounded-lg border px-4 py-2 transition-colors", style: {
                                                    borderColor: confirmation.type === 'message' ? '#2563eb' : '#d1d5db',
                                                    backgroundColor: confirmation.type === 'message' ? '#eff6ff' : 'transparent',
                                                }, children: [_jsx("input", { type: "radio", name: "confirmationType", value: "message", checked: confirmation.type === 'message', onChange: () => setConfirmation((c) => ({ ...c, type: 'message' })), className: "text-primary" }), _jsx(MessageSquare, { className: "h-4 w-4" }), _jsx("span", { className: "text-sm", children: "Show Message" })] }), _jsxs("label", { className: "hover:bg-muted flex cursor-pointer items-center gap-2 rounded-lg border px-4 py-2 transition-colors", style: {
                                                    borderColor: confirmation.type === 'redirect' ? '#2563eb' : '#d1d5db',
                                                    backgroundColor: confirmation.type === 'redirect' ? '#eff6ff' : 'transparent',
                                                }, children: [_jsx("input", { type: "radio", name: "confirmationType", value: "redirect", checked: confirmation.type === 'redirect', onChange: () => setConfirmation((c) => ({ ...c, type: 'redirect' })), className: "text-primary" }), _jsx(ExternalLink, { className: "h-4 w-4" }), _jsx("span", { className: "text-sm", children: "Redirect to Page" })] })] })] }), confirmation.type === 'message' ? (_jsxs("div", { children: [_jsx("label", { className: "text-foreground mb-1 block text-sm font-medium", children: "Success Message" }), _jsx("textarea", { value: confirmation.message, onChange: (e) => setConfirmation((c) => ({ ...c, message: e.target.value })), rows: 3, className: "border-border focus-visible:ring-ring/50 w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none", placeholder: "Thank you! Your submission has been received." })] })) : (_jsxs("div", { className: "grid gap-3", children: [_jsxs("div", { children: [_jsx("label", { className: "text-foreground mb-1 block text-sm font-medium", children: "Redirect URL" }), _jsx("input", { type: "url", value: confirmation.redirectUrl, onChange: (e) => setConfirmation((c) => ({ ...c, redirectUrl: e.target.value })), placeholder: "https://example.com/thank-you", className: "border-border focus-visible:ring-ring/50 w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none" })] }), _jsxs("div", { children: [_jsx("label", { className: "text-foreground mb-1 block text-sm font-medium", children: "Redirect Delay (ms)" }), _jsx("input", { type: "number", value: confirmation.redirectDelay, onChange: (e) => setConfirmation((c) => ({ ...c, redirectDelay: Number(e.target.value) })), min: 0, step: 500, className: "border-border focus-visible:ring-ring/50 w-32 rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none" }), _jsx("p", { className: "text-muted-foreground mt-1 text-xs", children: "0 = instant redirect" })] })] }))] }))] }), _jsxs("div", { className: "border-border bg-card mb-4 rounded-lg border", children: [_jsx("button", { onClick: () => toggleSection('analytics'), className: "hover:bg-muted flex w-full items-center justify-between p-4 transition-colors", children: _jsxs("div", { className: "flex items-center gap-2", children: [expandedSection === 'analytics' ? (_jsx(ChevronDown, { className: "h-4 w-4" })) : (_jsx(ChevronRight, { className: "h-4 w-4" })), _jsx(BarChart3, { className: "text-brand h-4 w-4" }), _jsx("span", { className: "text-foreground font-medium", children: "GA4 Analytics" }), _jsx("span", { className: `rounded px-2 py-0.5 text-xs ${analytics.enabled ? 'bg-success/10 text-success' : 'bg-muted text-muted-foreground'}`, children: analytics.enabled ? 'Enabled' : 'Disabled' })] }) }), expandedSection === 'analytics' && (_jsxs("div", { className: "border-border border-t p-4", children: [_jsxs("div", { className: "mb-4 flex items-center gap-3", children: [_jsxs("label", { className: "relative inline-flex cursor-pointer items-center", children: [_jsx("input", { type: "checkbox", checked: analytics.enabled, onChange: (e) => setAnalytics((a) => ({ ...a, enabled: e.target.checked })), className: "peer sr-only" }), _jsx("div", { className: "bg-muted peer peer-checked:bg-primary peer-focus:ring-ring/50 after:border-border after:bg-card h-5 w-9 rounded-full peer-focus:ring-2 peer-focus:outline-none after:absolute after:top-[2px] after:left-[2px] after:h-4 after:w-4 after:rounded-full after:border after:transition-all after:content-[''] peer-checked:after:translate-x-full peer-checked:after:border-white" })] }), _jsx("span", { className: "text-foreground text-sm font-medium", children: "Push events to Google Analytics 4" })] }), analytics.enabled && (_jsxs("div", { className: "grid gap-4 pl-12", children: [_jsxs("div", { children: [_jsxs("label", { className: "text-foreground mb-1 block text-sm font-medium", children: ["GA4 Measurement ID", _jsx("span", { className: "text-muted-foreground font-normal", children: " (optional)" })] }), _jsx("input", { type: "text", value: analytics.measurementId, onChange: (e) => setAnalytics((a) => ({ ...a, measurementId: e.target.value })), placeholder: "G-XXXXXXXXXX", className: "border-border focus-visible:ring-ring/50 w-64 rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none" }), _jsx("p", { className: "text-muted-foreground mt-1 text-xs", children: "Leave blank to use your site's default GA4 tag" })] }), _jsxs("div", { className: "grid grid-cols-2 gap-4", children: [_jsxs("div", { children: [_jsx("label", { className: "text-foreground mb-1 block text-sm font-medium", children: "Submit Event Name" }), _jsx("input", { type: "text", value: analytics.submitEventName, onChange: (e) => setAnalytics((a) => ({ ...a, submitEventName: e.target.value })), className: "border-border focus-visible:ring-ring/50 w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none" })] }), _jsxs("div", { children: [_jsx("label", { className: "text-foreground mb-1 block text-sm font-medium", children: "Start Event Name" }), _jsx("input", { type: "text", value: analytics.startEventName, onChange: (e) => setAnalytics((a) => ({ ...a, startEventName: e.target.value })), className: "border-border focus-visible:ring-ring/50 w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none" })] })] }), _jsxs("div", { className: "border-border border-t pt-4", children: [_jsxs("div", { className: "mb-3 flex items-center gap-3", children: [_jsx("input", { type: "checkbox", id: "trackConversion", checked: analytics.trackAsConversion, onChange: (e) => setAnalytics((a) => ({ ...a, trackAsConversion: e.target.checked })), className: "rounded" }), _jsx("label", { htmlFor: "trackConversion", className: "text-foreground text-sm font-medium", children: "Track as conversion event" })] }), analytics.trackAsConversion && (_jsxs("div", { className: "ml-6 grid grid-cols-2 gap-4", children: [_jsxs("div", { children: [_jsx("label", { className: "text-foreground mb-1 block text-sm font-medium", children: "Conversion Value" }), _jsx("input", { type: "number", value: analytics.conversionValue, onChange: (e) => setAnalytics((a) => ({ ...a, conversionValue: Number(e.target.value) })), min: 0, step: 0.01, className: "border-border focus-visible:ring-ring/50 w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none" })] }), _jsxs("div", { children: [_jsx("label", { className: "text-foreground mb-1 block text-sm font-medium", children: "Currency" }), _jsxs("select", { value: analytics.conversionCurrency, onChange: (e) => setAnalytics((a) => ({ ...a, conversionCurrency: e.target.value })), className: "border-border focus-visible:ring-ring/50 w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none", children: [_jsx("option", { value: "USD", children: "USD" }), _jsx("option", { value: "EUR", children: "EUR" }), _jsx("option", { value: "GBP", children: "GBP" }), _jsx("option", { value: "CAD", children: "CAD" }), _jsx("option", { value: "AUD", children: "AUD" })] })] })] }))] }), _jsx("div", { className: "border-info/30 bg-info/10 rounded-lg border p-3", children: _jsxs("p", { className: "text-foreground text-xs", children: [_jsx("strong", { children: "Note:" }), " Your site must have the GA4 snippet or GTM container installed. Actuate pushes events via", ' ', _jsx("code", { className: "bg-info/10 rounded px-1", children: "gtag()" }), " /", _jsx("code", { className: "bg-info/10 rounded px-1", children: "dataLayer" }), " \u2014 it does not load the GA4 script."] }) })] }))] }))] })] }));
}
//# sourceMappingURL=FormEditor.js.map