'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useEffect, useCallback } from 'react';
import { Plus, ArrowLeft, Edit, Trash2, Copy, Layers, Loader2, AlertTriangle, Calendar, Hash, } from 'lucide-react';
import { toast } from 'sonner';
import { cmsApi } from '../../lib/api.js';
import { createSection, createContainer, createRow, createColumn } from '@actuate-media/cms-core';
const CATEGORIES = ['header', 'footer', 'content', 'sidebar'];
const CATEGORY_COLORS = {
    header: 'bg-primary/10 text-primary',
    footer: 'bg-accent text-foreground',
    content: 'bg-muted text-muted-foreground',
    sidebar: 'bg-primary/10 text-primary',
};
function formatDate(dateStr) {
    return new Date(dateStr).toLocaleDateString(undefined, {
        month: 'short',
        day: 'numeric',
        year: 'numeric',
    });
}
function createEmptySectionTree() {
    const col = createColumn(100);
    const row = createRow([col]);
    const container = createContainer();
    container.children = [row];
    const section = createSection();
    section.children = [container];
    return section;
}
export function SavedSections({ onNavigate, config }) {
    const [sections, setSections] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [viewState, setViewState] = useState({ mode: 'list' });
    const [activeCategory, setActiveCategory] = useState('all');
    const [deleteConfirmId, setDeleteConfirmId] = useState(null);
    const [saving, setSaving] = useState(false);
    const fetchSections = useCallback(async () => {
        setLoading(true);
        setError(null);
        const res = await cmsApi('/saved-sections');
        if (res.error) {
            setError(res.error);
        }
        else {
            setSections(res.data ?? []);
        }
        setLoading(false);
    }, []);
    useEffect(() => {
        fetchSections();
    }, [fetchSections]);
    const filteredSections = activeCategory === 'all' ? sections : sections.filter((s) => s.category === activeCategory);
    async function handleDelete(id) {
        const res = await cmsApi(`/saved-sections/${id}`, { method: 'DELETE' });
        if (res.error) {
            toast.error(res.error);
        }
        else {
            toast.success('Section deleted');
            setSections((prev) => prev.filter((s) => s.id !== id));
        }
        setDeleteConfirmId(null);
    }
    async function handleDuplicate(section) {
        const res = await cmsApi('/saved-sections', {
            method: 'POST',
            body: JSON.stringify({
                name: `${section.name} (Copy)`,
                description: section.description,
                category: section.category,
                tree: section.tree,
            }),
        });
        if (res.error) {
            toast.error(res.error);
        }
        else {
            toast.success('Section duplicated');
            fetchSections();
        }
    }
    if (viewState.mode === 'create' || viewState.mode === 'edit') {
        return (_jsx(SectionForm, { initial: viewState.mode === 'edit' ? viewState.section : undefined, saving: saving, onSave: async (data) => {
                setSaving(true);
                if (viewState.mode === 'create') {
                    const res = await cmsApi('/saved-sections', {
                        method: 'POST',
                        body: JSON.stringify({ ...data, tree: createEmptySectionTree() }),
                    });
                    setSaving(false);
                    if (res.error) {
                        toast.error(res.error);
                    }
                    else {
                        toast.success('Section created');
                        setViewState({ mode: 'list' });
                        fetchSections();
                    }
                }
                else {
                    const res = await cmsApi(`/saved-sections/${viewState.section.id}`, {
                        method: 'PUT',
                        body: JSON.stringify(data),
                    });
                    setSaving(false);
                    if (res.error) {
                        toast.error(res.error);
                    }
                    else {
                        toast.success('Section updated');
                        setViewState({ mode: 'list' });
                        fetchSections();
                    }
                }
            }, onCancel: () => setViewState({ mode: 'list' }) }));
    }
    return (_jsxs("div", { className: "p-4 pr-8", children: [_jsxs("div", { className: "mb-6 flex items-center justify-between", children: [_jsxs("div", { children: [_jsx("h1", { className: "text-foreground text-2xl font-medium", children: "Saved Sections" }), _jsx("p", { className: "text-muted-foreground mt-1 text-sm", children: "Reusable sections for the page builder" })] }), _jsxs("button", { type: "button", onClick: () => setViewState({ mode: 'create' }), className: "bg-primary text-primary-foreground hover:bg-primary/90 flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition-colors", children: [_jsx(Plus, { size: 16 }), "Create Section"] })] }), _jsxs("div", { className: "border-border mb-4 flex items-center gap-1 border-b", children: [_jsx(CategoryTab, { label: "All", active: activeCategory === 'all', onClick: () => setActiveCategory('all') }), CATEGORIES.map((cat) => (_jsx(CategoryTab, { label: cat.charAt(0).toUpperCase() + cat.slice(1), active: activeCategory === cat, onClick: () => setActiveCategory(cat) }, cat)))] }), loading && (_jsx("div", { className: "flex items-center justify-center py-16", children: _jsx(Loader2, { className: "text-muted-foreground h-6 w-6 animate-spin" }) })), error && !loading && (_jsxs("div", { className: "flex flex-col items-center justify-center py-12 text-center", children: [_jsx(AlertTriangle, { size: 24, className: "text-destructive mb-2" }), _jsx("p", { className: "text-muted-foreground mb-3 text-sm", children: error }), _jsx("button", { type: "button", onClick: fetchSections, className: "text-foreground border-border hover:bg-accent rounded-md border px-3 py-1.5 text-sm font-medium transition-colors", children: "Retry" })] })), !loading && !error && filteredSections.length === 0 && (_jsxs("div", { className: "flex flex-col items-center justify-center py-16 text-center", children: [_jsx(Layers, { size: 32, className: "text-muted-foreground mb-3" }), _jsx("p", { className: "text-foreground mb-1 text-sm font-medium", children: "No saved sections" }), _jsx("p", { className: "text-muted-foreground mb-4 text-xs", children: activeCategory === 'all'
                            ? 'Create your first reusable section to get started.'
                            : `No sections in the "${activeCategory}" category.` }), activeCategory === 'all' && (_jsxs("button", { type: "button", onClick: () => setViewState({ mode: 'create' }), className: "bg-primary text-primary-foreground hover:bg-primary/90 flex items-center gap-2 rounded-md px-3 py-1.5 text-sm font-medium transition-colors", children: [_jsx(Plus, { size: 14 }), "Create Section"] }))] })), !loading && !error && filteredSections.length > 0 && (_jsx("div", { className: "grid grid-cols-1 gap-3 lg:grid-cols-2", children: filteredSections.map((section) => (_jsxs("div", { className: "border-border bg-card hover:border-primary/50 rounded-lg border p-4 transition-colors", children: [_jsxs("div", { className: "flex items-start justify-between gap-3", children: [_jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("p", { className: "text-foreground truncate text-sm font-medium", children: section.name }), section.description && (_jsx("p", { className: "text-muted-foreground mt-0.5 line-clamp-2 text-xs", children: section.description }))] }), _jsx("span", { className: `shrink-0 rounded-full px-2 py-0.5 text-xs ${CATEGORY_COLORS[section.category] ?? 'bg-muted text-muted-foreground'}`, children: section.category })] }), _jsxs("div", { className: "text-muted-foreground mt-3 flex items-center gap-4 text-xs", children: [_jsxs("span", { className: "flex items-center gap-1", children: [_jsx(Hash, { size: 12 }), section.usageCount, " use", section.usageCount !== 1 ? 's' : ''] }), _jsxs("span", { className: "flex items-center gap-1", children: [_jsx(Calendar, { size: 12 }), formatDate(section.createdAt)] }), section.tree && (_jsxs("span", { className: "flex items-center gap-1", children: [_jsx(Layers, { size: 12 }), JSON.stringify(section.tree).length > 1000 ? 'Complex' : 'Simple'] }))] }), _jsxs("div", { className: "border-border mt-3 flex items-center gap-1 border-t pt-3", children: [_jsxs("button", { type: "button", onClick: () => setViewState({ mode: 'edit', section }), className: "text-foreground hover:bg-accent flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-xs font-medium transition-colors", "aria-label": `Edit ${section.name}`, children: [_jsx(Edit, { size: 13 }), "Edit"] }), _jsxs("button", { type: "button", onClick: () => handleDuplicate(section), className: "text-foreground hover:bg-accent flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-xs font-medium transition-colors", "aria-label": `Duplicate ${section.name}`, children: [_jsx(Copy, { size: 13 }), "Duplicate"] }), deleteConfirmId === section.id ? (_jsxs("div", { className: "ml-auto flex items-center gap-1", children: [_jsx("span", { className: "text-destructive mr-1 text-xs", children: "Delete?" }), _jsx("button", { type: "button", onClick: () => handleDelete(section.id), className: "text-destructive-foreground bg-destructive hover:bg-destructive/90 rounded-md px-2 py-1 text-xs font-medium transition-colors", children: "Yes" }), _jsx("button", { type: "button", onClick: () => setDeleteConfirmId(null), className: "text-foreground border-border hover:bg-accent rounded-md border px-2 py-1 text-xs font-medium transition-colors", children: "No" })] })) : (_jsxs("button", { type: "button", onClick: () => setDeleteConfirmId(section.id), className: "text-destructive hover:bg-destructive/10 ml-auto flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-xs font-medium transition-colors", "aria-label": `Delete ${section.name}`, children: [_jsx(Trash2, { size: 13 }), "Delete"] }))] })] }, section.id))) }))] }));
}
function CategoryTab({ label, active, onClick }) {
    return (_jsx("button", { type: "button", onClick: onClick, className: `-mb-px border-b-2 px-3 py-2 text-sm transition-colors ${active
            ? 'border-primary text-foreground font-medium'
            : 'text-muted-foreground hover:text-foreground border-transparent'}`, children: label }));
}
function SectionForm({ initial, saving, onSave, onCancel }) {
    const [name, setName] = useState(initial?.name ?? '');
    const [description, setDescription] = useState(initial?.description ?? '');
    const [category, setCategory] = useState(initial?.category ?? 'content');
    function handleSubmit(e) {
        e.preventDefault();
        if (!name.trim())
            return;
        onSave({ name: name.trim(), description: description.trim(), category });
    }
    const treeSize = initial?.tree ? JSON.stringify(initial.tree).length : null;
    return (_jsxs("div", { className: "p-4 pr-8", children: [_jsxs("div", { className: "mb-6", children: [_jsxs("button", { type: "button", onClick: onCancel, className: "text-muted-foreground hover:text-foreground mb-3 flex items-center gap-1.5 text-sm transition-colors", "aria-label": "Back to saved sections", children: [_jsx(ArrowLeft, { size: 16 }), "Back"] }), _jsx("h1", { className: "text-foreground text-2xl font-medium", children: initial ? `Edit: ${initial.name}` : 'Create Saved Section' })] }), _jsxs("form", { onSubmit: handleSubmit, className: "max-w-lg space-y-4", children: [_jsxs("div", { children: [_jsxs("label", { htmlFor: "section-name", className: "text-foreground mb-1 block text-sm font-medium", children: ["Name ", _jsx("span", { className: "text-destructive", children: "*" })] }), _jsx("input", { id: "section-name", type: "text", value: name, onChange: (e) => setName(e.target.value), required: true, placeholder: "e.g. Hero Banner", className: "bg-background border-input focus:ring-ring w-full rounded-md border px-3 py-2 text-sm focus:ring-2 focus:outline-none" })] }), _jsxs("div", { children: [_jsx("label", { htmlFor: "section-description", className: "text-foreground mb-1 block text-sm font-medium", children: "Description" }), _jsx("textarea", { id: "section-description", value: description, onChange: (e) => setDescription(e.target.value), placeholder: "Optional description of this section...", rows: 3, className: "bg-background border-input focus:ring-ring w-full resize-none rounded-md border px-3 py-2 text-sm focus:ring-2 focus:outline-none" })] }), _jsxs("div", { children: [_jsx("label", { htmlFor: "section-category", className: "text-foreground mb-1 block text-sm font-medium", children: "Category" }), _jsx("select", { id: "section-category", value: category, onChange: (e) => setCategory(e.target.value), className: "bg-background border-input focus:ring-ring w-full rounded-md border px-3 py-2 text-sm focus:ring-2 focus:outline-none", children: CATEGORIES.map((cat) => (_jsx("option", { value: cat, children: cat.charAt(0).toUpperCase() + cat.slice(1) }, cat))) })] }), treeSize !== null && (_jsx("div", { className: "border-border bg-muted rounded-md border p-3", children: _jsxs("p", { className: "text-muted-foreground text-xs", children: ["Section tree editing is available in the page builder. Current tree size:", ' ', (treeSize / 1024).toFixed(1), " KB"] }) })), _jsxs("div", { className: "flex items-center gap-3 pt-2", children: [_jsxs("button", { type: "submit", 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 font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50", children: [saving && _jsx(Loader2, { size: 14, className: "animate-spin" }), initial ? 'Save Changes' : 'Create Section'] }), _jsx("button", { type: "button", onClick: onCancel, disabled: saving, className: "text-foreground border-border hover:bg-accent rounded-lg border px-4 py-2 text-sm font-medium transition-colors disabled:opacity-50", children: "Cancel" })] })] })] }));
}
//# sourceMappingURL=SavedSections.js.map