'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { ChevronRight, ChevronDown, FolderOpen, Folder as FolderIcon, Plus, MoreHorizontal, Pencil, Trash2, FolderPlus, Clock, Inbox, LayoutGrid, Loader2, } from 'lucide-react';
import { useState, useEffect, useCallback, useRef } from 'react';
import { toast } from 'sonner';
import { cmsApi } from '../lib/api.js';
export function FolderTree({ scope, selected, onSelect, itemCounts, totalCount, recentCount, uncategorizedCount, onDropItem, }) {
    const [folders, setFolders] = useState([]);
    const [loading, setLoading] = useState(true);
    const [expanded, setExpanded] = useState(new Set());
    const [editingId, setEditingId] = useState(null);
    const [editName, setEditName] = useState('');
    const [contextMenu, setContextMenu] = useState(null);
    const [creatingIn, setCreatingIn] = useState(false);
    const [newFolderName, setNewFolderName] = useState('');
    const newFolderInputRef = useRef(null);
    const editInputRef = useRef(null);
    const [dragOverId, setDragOverId] = useState(null);
    const fetchFolders = useCallback(async () => {
        const res = await cmsApi(`/folders?scope=${scope}`);
        if (res.data)
            setFolders(res.data);
        setLoading(false);
    }, [scope]);
    useEffect(() => {
        fetchFolders();
    }, [fetchFolders]);
    useEffect(() => {
        if (creatingIn !== false && newFolderInputRef.current) {
            newFolderInputRef.current.focus();
        }
    }, [creatingIn]);
    useEffect(() => {
        if (editingId && editInputRef.current) {
            editInputRef.current.focus();
            editInputRef.current.select();
        }
    }, [editingId]);
    useEffect(() => {
        const handleClick = () => setContextMenu(null);
        document.addEventListener('click', handleClick);
        return () => document.removeEventListener('click', handleClick);
    }, []);
    const toggleExpand = (id) => {
        setExpanded((prev) => {
            const next = new Set(prev);
            if (next.has(id))
                next.delete(id);
            else
                next.add(id);
            return next;
        });
    };
    const handleCreate = async (parentId) => {
        if (!newFolderName.trim()) {
            setCreatingIn(false);
            return;
        }
        const res = await cmsApi('/folders', {
            method: 'POST',
            body: JSON.stringify({ name: newFolderName.trim(), scope, parentId }),
        });
        if (res.error) {
            toast.error(res.error);
        }
        else {
            toast.success('Folder created');
            if (parentId)
                setExpanded((prev) => new Set(prev).add(parentId));
            fetchFolders();
        }
        setNewFolderName('');
        setCreatingIn(false);
    };
    const handleRename = async (id) => {
        if (!editName.trim()) {
            setEditingId(null);
            return;
        }
        const res = await cmsApi(`/folders/${id}`, {
            method: 'PUT',
            body: JSON.stringify({ name: editName.trim() }),
        });
        if (res.error)
            toast.error(res.error);
        else
            fetchFolders();
        setEditingId(null);
    };
    const handleDelete = async (id) => {
        const res = await cmsApi(`/folders/${id}`, { method: 'DELETE' });
        if (res.error)
            toast.error(res.error);
        else {
            toast.success('Folder deleted');
            if (selected.type === 'folder' && selected.folderId === id) {
                onSelect({ type: 'smart', smart: 'all' });
            }
            fetchFolders();
        }
    };
    const isSelected = (sel) => {
        if (selected.type !== sel.type)
            return false;
        if (sel.type === 'smart')
            return selected.smart === sel.smart;
        return selected.folderId === sel.folderId;
    };
    const handleDragOver = (e, folderId) => {
        e.preventDefault();
        e.stopPropagation();
        setDragOverId(folderId);
    };
    const handleDragLeave = () => {
        setDragOverId(null);
    };
    const handleDrop = (e, folderId) => {
        e.preventDefault();
        e.stopPropagation();
        setDragOverId(null);
        const itemId = e.dataTransfer.getData('text/actuate-item-id');
        if (itemId && onDropItem) {
            onDropItem(itemId, folderId);
        }
    };
    const countForFolder = (id) => itemCounts?.[id];
    const renderFolder = (folder, depth) => {
        const isExpanded = expanded.has(folder.id);
        const hasChildren = folder.children.length > 0;
        const isActive = isSelected({ type: 'folder', folderId: folder.id });
        const isDragOver = dragOverId === folder.id;
        const count = countForFolder(folder.id);
        return (_jsxs("div", { children: [_jsxs("div", { className: `group flex cursor-pointer items-center gap-1 rounded-md px-2 py-1.5 text-sm transition-colors ${isActive
                        ? 'bg-primary/10 text-primary font-medium'
                        : isDragOver
                            ? 'bg-primary/15 ring-primary/40 ring-2'
                            : 'text-foreground hover:bg-muted'}`, style: { paddingLeft: `${8 + depth * 16}px` }, onClick: () => onSelect({ type: 'folder', folderId: folder.id }), onContextMenu: (e) => {
                        e.preventDefault();
                        setContextMenu({ id: folder.id, x: e.clientX, y: e.clientY });
                    }, onDragOver: (e) => handleDragOver(e, folder.id), onDragLeave: handleDragLeave, onDrop: (e) => handleDrop(e, folder.id), children: [_jsx("button", { type: "button", className: `hover:bg-muted rounded p-0.5 transition-colors ${hasChildren ? '' : 'invisible'}`, onClick: (e) => {
                                e.stopPropagation();
                                toggleExpand(folder.id);
                            }, children: isExpanded ? (_jsx(ChevronDown, { className: "h-3.5 w-3.5" })) : (_jsx(ChevronRight, { className: "h-3.5 w-3.5" })) }), isExpanded ? (_jsx(FolderOpen, { className: "text-primary h-4 w-4 shrink-0" })) : (_jsx(FolderIcon, { className: "text-muted-foreground h-4 w-4 shrink-0" })), editingId === folder.id ? (_jsx("input", { ref: editInputRef, type: "text", value: editName, onChange: (e) => setEditName(e.target.value), onBlur: () => handleRename(folder.id), onKeyDown: (e) => {
                                if (e.key === 'Enter')
                                    handleRename(folder.id);
                                if (e.key === 'Escape')
                                    setEditingId(null);
                            }, className: "border-primary/50 focus:ring-ring min-w-0 flex-1 rounded border px-1 py-0 text-sm focus:ring-1 focus:outline-none", onClick: (e) => e.stopPropagation() })) : (_jsx("span", { className: "min-w-0 flex-1 truncate", children: folder.name })), count !== undefined && !editingId && (_jsx("span", { className: "text-muted-foreground text-xs tabular-nums", children: count })), _jsx("button", { type: "button", className: "hover:bg-muted rounded p-0.5 opacity-0 transition-all group-hover:opacity-100", onClick: (e) => {
                                e.stopPropagation();
                                setContextMenu({ id: folder.id, x: e.clientX, y: e.clientY });
                            }, children: _jsx(MoreHorizontal, { className: "text-muted-foreground h-3.5 w-3.5" }) })] }), isExpanded && (_jsxs("div", { children: [folder.children.map((child) => renderFolder(child, depth + 1)), creatingIn === folder.id && (_jsxs("div", { className: "flex items-center gap-1 px-2 py-1", style: { paddingLeft: `${24 + (depth + 1) * 16}px` }, children: [_jsx(FolderIcon, { className: "text-muted-foreground h-4 w-4 shrink-0" }), _jsx("input", { ref: newFolderInputRef, type: "text", value: newFolderName, onChange: (e) => setNewFolderName(e.target.value), onBlur: () => handleCreate(folder.id), onKeyDown: (e) => {
                                        if (e.key === 'Enter')
                                            handleCreate(folder.id);
                                        if (e.key === 'Escape') {
                                            setCreatingIn(false);
                                            setNewFolderName('');
                                        }
                                    }, placeholder: "Folder name...", className: "border-primary/50 focus:ring-ring min-w-0 flex-1 rounded border px-1 py-0 text-sm focus:ring-1 focus:outline-none" })] }))] }))] }, folder.id));
    };
    if (loading) {
        return (_jsx("div", { className: "flex items-center justify-center py-8", children: _jsx(Loader2, { className: "text-muted-foreground h-5 w-5 animate-spin" }) }));
    }
    return (_jsxs("div", { className: "flex h-full flex-col", children: [_jsxs("div", { className: "space-y-0.5 px-1 py-2", children: [_jsxs("button", { type: "button", className: `flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors ${isSelected({ type: 'smart', smart: 'all' })
                            ? 'bg-primary/10 text-primary font-medium'
                            : 'text-foreground hover:bg-muted'}`, onClick: () => onSelect({ type: 'smart', smart: 'all' }), onDragOver: (e) => handleDragOver(e, null), onDragLeave: handleDragLeave, onDrop: (e) => handleDrop(e, null), children: [_jsx(LayoutGrid, { className: "h-4 w-4 shrink-0" }), _jsx("span", { className: "flex-1 text-left", children: "All" }), totalCount !== undefined && (_jsx("span", { className: "text-muted-foreground text-xs tabular-nums", children: totalCount }))] }), _jsxs("button", { type: "button", className: `flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors ${isSelected({ type: 'smart', smart: 'recent' })
                            ? 'bg-primary/10 text-primary font-medium'
                            : 'text-foreground hover:bg-muted'}`, onClick: () => onSelect({ type: 'smart', smart: 'recent' }), children: [_jsx(Clock, { className: "h-4 w-4 shrink-0" }), _jsx("span", { className: "flex-1 text-left", children: "Recent" }), recentCount !== undefined && (_jsx("span", { className: "text-muted-foreground text-xs tabular-nums", children: recentCount }))] }), _jsxs("button", { type: "button", className: `flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors ${isSelected({ type: 'smart', smart: 'uncategorized' })
                            ? 'bg-primary/10 text-primary font-medium'
                            : 'text-foreground hover:bg-muted'}`, onClick: () => onSelect({ type: 'smart', smart: 'uncategorized' }), children: [_jsx(Inbox, { className: "h-4 w-4 shrink-0" }), _jsx("span", { className: "flex-1 text-left", children: "Uncategorized" }), uncategorizedCount !== undefined && (_jsx("span", { className: "text-muted-foreground text-xs tabular-nums", children: uncategorizedCount }))] })] }), _jsx("div", { className: "border-border my-1 border-t" }), _jsxs("div", { className: "flex-1 space-y-0.5 overflow-y-auto px-1 py-1", children: [folders.map((folder) => renderFolder(folder, 0)), creatingIn === null && (_jsxs("div", { className: "flex items-center gap-1 px-2 py-1", children: [_jsx(FolderIcon, { className: "text-muted-foreground ml-5 h-4 w-4 shrink-0" }), _jsx("input", { ref: newFolderInputRef, type: "text", value: newFolderName, onChange: (e) => setNewFolderName(e.target.value), onBlur: () => handleCreate(null), onKeyDown: (e) => {
                                    if (e.key === 'Enter')
                                        handleCreate(null);
                                    if (e.key === 'Escape') {
                                        setCreatingIn(false);
                                        setNewFolderName('');
                                    }
                                }, placeholder: "Folder name...", className: "border-primary/50 focus:ring-ring min-w-0 flex-1 rounded border px-1 py-0 text-sm focus:ring-1 focus:outline-none" })] }))] }), _jsx("div", { className: "border-border border-t p-2", children: _jsxs("button", { type: "button", onClick: () => {
                        setCreatingIn(null);
                        setNewFolderName('');
                    }, className: "text-muted-foreground hover:bg-muted flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors", children: [_jsx(Plus, { className: "h-4 w-4" }), "New Folder"] }) }), contextMenu && (_jsxs("div", { className: "border-border bg-card fixed z-50 min-w-[160px] rounded-lg border py-1 shadow-lg", style: { left: contextMenu.x, top: contextMenu.y }, children: [_jsxs("button", { type: "button", className: "text-foreground hover:bg-muted flex w-full items-center gap-2 px-3 py-1.5 text-sm transition-colors", onClick: () => {
                            const folder = findFolder(folders, contextMenu.id);
                            if (folder) {
                                setEditingId(folder.id);
                                setEditName(folder.name);
                            }
                            setContextMenu(null);
                        }, children: [_jsx(Pencil, { className: "h-3.5 w-3.5" }), "Rename"] }), _jsxs("button", { type: "button", className: "text-foreground hover:bg-muted flex w-full items-center gap-2 px-3 py-1.5 text-sm transition-colors", onClick: () => {
                            setCreatingIn(contextMenu.id);
                            setNewFolderName('');
                            setExpanded((prev) => new Set(prev).add(contextMenu.id));
                            setContextMenu(null);
                        }, children: [_jsx(FolderPlus, { className: "h-3.5 w-3.5" }), "New Subfolder"] }), _jsx("div", { className: "border-border my-1 border-t" }), _jsxs("button", { type: "button", className: "text-destructive hover:bg-destructive/10 flex w-full items-center gap-2 px-3 py-1.5 text-sm transition-colors", onClick: () => {
                            handleDelete(contextMenu.id);
                            setContextMenu(null);
                        }, children: [_jsx(Trash2, { className: "h-3.5 w-3.5" }), "Delete"] })] }))] }));
}
function findFolder(nodes, id) {
    for (const n of nodes) {
        if (n.id === id)
            return n;
        const found = findFolder(n.children, id);
        if (found)
            return found;
    }
    return null;
}
//# sourceMappingURL=FolderTree.js.map