import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState } from "react";
import { SimpleToolbar } from "../ui/SimpleToolbar";
import { SimpleIconButton } from "../ui/SimpleIconButton";
import { Plus, X, ExternalLink, Trash2, Check, MessageSquare, Lightbulb, } from "lucide-react";
import { Button } from "../../components/ui/button";
import { Checkbox } from "../../components/ui/checkbox";
import { Badge } from "../../components/ui/badge";
import { Popover, PopoverContent, PopoverTrigger, } from "../../components/ui/popover";
import { useEditContext } from "../client/editContext";
import { ItemTreeSelector } from "./ItemTreeSelector";
export function PagesPanel({ items, reviewId, onAddPages, onRemovePages, loading, language, }) {
    const selectionKeySeparator = "|||";
    const toSelectionKey = (itemId, itemLanguage) => `${itemId}${selectionKeySeparator}${itemLanguage}`;
    const fromSelectionKey = (key) => {
        const separatorIndex = key.indexOf(selectionKeySeparator);
        if (separatorIndex === -1)
            return null;
        const itemId = key.slice(0, separatorIndex);
        const language = key.slice(separatorIndex + selectionKeySeparator.length);
        if (!itemId || !language)
            return null;
        return { itemId, language };
    };
    const [isAddPopoverOpen, setIsAddPopoverOpen] = useState(false);
    const [selectedItems, setSelectedItems] = useState([]);
    const [selectedPagesForRemoval, setSelectedPagesForRemoval] = useState(new Set());
    const editContext = useEditContext();
    const isLimitedPreviewUser = editContext?.user?.isLimitedPreviewUser ?? false;
    const handleItemsChange = (descriptors) => {
        setSelectedItems(descriptors);
    };
    const handleAddSelectedPages = async () => {
        if (selectedItems.length > 0) {
            const itemsToAdd = selectedItems.map((desc) => ({
                descriptor: desc,
                includeSubitems: false,
            }));
            await onAddPages(itemsToAdd);
            setSelectedItems([]);
            setIsAddPopoverOpen(false);
        }
    };
    const handleRemovePage = async (itemId, language) => {
        const itemKey = toSelectionKey(itemId, language);
        const item = items.find((i) => toSelectionKey(i.itemId, i.language) === itemKey);
        const itemName = item?.name || item?.path || itemId;
        editContext?.confirm({
            header: "Remove Page",
            message: `Are you sure you want to remove "${itemName}" from this review?`,
            acceptLabel: "Remove",
            showCancel: true,
            accept: async () => {
                await onRemovePages([
                    {
                        id: itemId,
                        language,
                        version: 0, // Version not required by remove endpoint
                    },
                ]);
            },
        });
    };
    const handleRemoveSelectedPages = async () => {
        if (selectedPagesForRemoval.size === 0)
            return;
        const pagesToRemove = Array.from(selectedPagesForRemoval)
            .map((key) => fromSelectionKey(key))
            .filter((parsed) => !!parsed);
        const itemDescriptors = pagesToRemove.map(({ itemId, language }) => ({
            id: itemId,
            language,
            version: 0,
        }));
        const pageNames = pagesToRemove.map(({ itemId, language }) => {
            const item = items.find((i) => i.itemId === itemId && i.language === language);
            return item?.name || item?.path || itemId;
        });
        const message = selectedPagesForRemoval.size === 1
            ? `Are you sure you want to remove "${pageNames[0]}" from this review?`
            : `Are you sure you want to remove ${selectedPagesForRemoval.size} pages from this review?`;
        editContext?.confirm({
            header: "Remove Pages",
            message,
            acceptLabel: "Remove",
            showCancel: true,
            accept: async () => {
                await onRemovePages(itemDescriptors);
                setSelectedPagesForRemoval(new Set());
            },
        });
    };
    const togglePageSelection = (itemId, language) => {
        const key = toSelectionKey(itemId, language);
        const newSelection = new Set(selectedPagesForRemoval);
        if (newSelection.has(key)) {
            newSelection.delete(key);
        }
        else {
            newSelection.add(key);
        }
        setSelectedPagesForRemoval(newSelection);
    };
    const hasSelectedPages = selectedPagesForRemoval.size > 0;
    return (_jsxs("div", { className: "flex h-full flex-col", children: [_jsx(SimpleToolbar, { children: !isLimitedPreviewUser && (_jsxs(_Fragment, { children: [_jsxs(Popover, { open: isAddPopoverOpen, onOpenChange: setIsAddPopoverOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsx(SimpleIconButton, { label: "Add Pages", icon: _jsx(Plus, { className: "h-4 w-4" }), onClick: () => setIsAddPopoverOpen(true) }) }), _jsx(PopoverContent, { className: "m-2 w-[600px] p-0", align: "start", children: _jsxs("div", { className: "flex flex-col gap-2 p-2", children: [_jsx("div", { className: "text-sm font-medium", children: "Select Pages" }), _jsx(ItemTreeSelector, { selectedItems: selectedItems, onItemsChange: handleItemsChange, language: language, height: "350px" }), _jsxs("div", { className: "flex justify-end gap-2 border-t pt-2", children: [_jsx(Button, { variant: "outline", size: "sm", onClick: () => {
                                                            setSelectedItems([]);
                                                            setIsAddPopoverOpen(false);
                                                        }, children: "Cancel" }), _jsxs(Button, { size: "sm", onClick: handleAddSelectedPages, disabled: selectedItems.length === 0 || loading, children: [_jsx(Plus, { className: "mr-2 h-4 w-4" }), "Add", " ", selectedItems.length > 0
                                                                ? `${selectedItems.length} `
                                                                : "", "Page", selectedItems.length !== 1 ? "s" : ""] })] })] }) })] }), hasSelectedPages && (_jsx(SimpleIconButton, { label: "Remove Selected", icon: _jsx(Trash2, { className: "h-4 w-4" }), onClick: handleRemoveSelectedPages, disabled: loading }))] })) }), _jsx("div", { className: "flex-1 overflow-y-auto p-2", children: items.length === 0 ? (_jsx("div", { className: "flex h-full items-center justify-center text-sm text-gray-500", children: "No pages in review" })) : (_jsx("div", { className: "space-y-2", children: items.map((item, index) => {
                        const itemKey = toSelectionKey(item.itemId, item.language);
                        const isSelected = selectedPagesForRemoval.has(itemKey);
                        return (_jsx("div", { className: "rounded border p-3 hover:bg-gray-50", children: _jsxs("div", { className: "flex items-start justify-between", children: [_jsxs("div", { className: "flex flex-1 items-start gap-2", children: [_jsx("div", { className: "mt-0.5", children: _jsx(Checkbox, { checked: isSelected, onCheckedChange: () => {
                                                        if (!isLimitedPreviewUser) {
                                                            togglePageSelection(item.itemId, item.language);
                                                        }
                                                    }, disabled: isLimitedPreviewUser, onClick: (e) => e.stopPropagation() }) }), _jsxs("div", { className: "flex-1", children: [_jsx("div", { className: "text-sm font-medium", children: item.name || item.path || item.itemId }), _jsxs("div", { className: "mt-1 flex items-center gap-2", children: [_jsxs("div", { className: "text-xs text-gray-500", children: [item.language, item.includeSubitems && " (with subitems)"] }), item.decisionsCount !== undefined &&
                                                                item.decisionsCount > 0 && (_jsxs(Badge, { variant: "outline", className: "h-5 px-1.5 text-xs", children: [_jsx(Check, { className: "mr-1 h-3 w-3" }), item.decisionsCount] })), item.commentsCount !== undefined &&
                                                                item.commentsCount > 0 && (_jsxs(Badge, { variant: "outline", className: "h-5 px-1.5 text-xs", children: [_jsx(MessageSquare, { className: "mr-1 h-3 w-3" }), item.commentsCount] })), item.suggestionsCount !== undefined &&
                                                                item.suggestionsCount > 0 && (_jsxs(Badge, { variant: "outline", className: "h-5 px-1.5 text-xs", children: [_jsx(Lightbulb, { className: "mr-1 h-3 w-3" }), item.suggestionsCount] }))] })] })] }), _jsxs("div", { className: "flex items-center gap-1", children: [_jsx(Button, { variant: "ghost", size: "sm", onClick: () => {
                                                    console.log("[PagesPanel] Loading item from pages panel:", {
                                                        itemId: item.itemId,
                                                        language: item.language,
                                                        isLimitedPreviewUser,
                                                        timestamp: new Date().toISOString(),
                                                    });
                                                    if (editContext?.loadItem) {
                                                        editContext.loadItem({
                                                            id: item.itemId,
                                                            language: item.language,
                                                            version: 0,
                                                        });
                                                    }
                                                    else {
                                                        console.error("[PagesPanel] editContext.loadItem is not available");
                                                    }
                                                }, title: "Open in editor", children: _jsx(ExternalLink, { className: "h-3 w-3" }) }), !isLimitedPreviewUser && (_jsx(Button, { variant: "ghost", size: "sm", onClick: () => handleRemovePage(item.itemId, item.language), disabled: loading, children: _jsx(X, { className: "h-4 w-4" }) }))] })] }) }, `${item.itemId}-${item.language}-${index}`));
                    }) })) })] }));
}
//# sourceMappingURL=PagesPanel.js.map