import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useState } from "react";
import { ClipboardCheck, Loader2 } from "lucide-react";
import { Dialog, DialogContent } from "../../components/ui/dialog";
import { StyledDialogTitle } from "../../components/ui/styled-dialog-title";
import { Button } from "../../components/ui/button";
import { Input } from "../../components/ui/input";
import { Label } from "../../components/ui/label";
import { useEditContext } from "../../editor/client/editContext";
import { ItemCollectionEditor, } from "../../editor/ui/ItemCollectionEditor";
import { createItemCollection, getItemCollectionDetails, updateItemCollection, } from "../services/taskService";
import DialogButtons from "../../editor/ui/DialogButtons";
const CONTENT_ROOT_ID = "0de95ae4-41ab-4d01-9eb0-67441b7c2450";
export function ItemCollectionEditorDialog(props) {
    const { open, onOpenChange, onConfirm, existingCollectionId } = props;
    const editContext = useEditContext();
    const language = editContext?.currentItemDescriptor?.language ?? "en";
    const rootItemIds = useMemo(() => [CONTENT_ROOT_ID], []);
    const [name, setName] = useState("");
    const [items, setItems] = useState([]);
    const [selectedInTree, setSelectedInTree] = useState([]);
    const [selectedFromList, setSelectedFromList] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const resetState = useCallback(() => {
        setName("");
        setItems([]);
        setSelectedInTree([]);
        setSelectedFromList([]);
        setError(null);
    }, []);
    useEffect(() => {
        if (!open)
            return;
        if (!existingCollectionId) {
            resetState();
            setLoading(false);
            return;
        }
        let disposed = false;
        setLoading(true);
        getItemCollectionDetails(existingCollectionId)
            .then(async (result) => {
            if (disposed || result.type !== "success" || !result.data)
                return;
            const raw = result.data;
            const loadedName = raw.name ?? "";
            const loadedItems = raw.items ?? [];
            setName(loadedName ?? "");
            const norm = (i) => ({
                itemId: i.itemId ?? "",
                language: i.language ?? language,
                includeSubitems: i.includeSubitems ?? false,
            });
            const validItems = Array.isArray(loadedItems)
                ? loadedItems.filter((i) => norm(i).itemId)
                : [];
            if (validItems.length === 0) {
                setItems([]);
                setLoading(false);
                return;
            }
            const itemsWithStubs = [];
            if (editContext?.itemsRepository) {
                try {
                    const stubs = await editContext.itemsRepository.getItemsStubs(validItems.map((i) => {
                        const { itemId, language: lang } = norm(i);
                        return { id: itemId, language: lang || language, version: 1 };
                    }));
                    const stubMap = new Map(stubs.map((s) => [s.id, s]));
                    for (const i of validItems) {
                        const { itemId, language: lang, includeSubitems: inc } = norm(i);
                        const stub = stubMap.get(itemId);
                        itemsWithStubs.push({
                            descriptor: {
                                id: itemId,
                                language: lang || language,
                                version: 1,
                                name: stub?.name ?? "",
                                displayName: stub?.displayName ?? "",
                                path: stub?.path ?? "",
                            },
                            includeSubitems: inc,
                        });
                    }
                }
                catch {
                    for (const i of validItems) {
                        const { itemId, language: lang, includeSubitems: inc } = norm(i);
                        itemsWithStubs.push({
                            descriptor: {
                                id: itemId,
                                language: lang || language,
                                version: 1,
                                name: "",
                                displayName: "",
                                path: "",
                            },
                            includeSubitems: inc,
                        });
                    }
                }
            }
            else {
                for (const i of validItems) {
                    const { itemId, language: lang, includeSubitems: inc } = norm(i);
                    itemsWithStubs.push({
                        descriptor: {
                            id: itemId,
                            language: lang || language,
                            version: 1,
                            name: "",
                            displayName: "",
                            path: "",
                        },
                        includeSubitems: inc,
                    });
                }
            }
            if (!disposed)
                setItems(itemsWithStubs);
        })
            .catch(() => {
            if (!disposed)
                setError("Failed to load collection");
        })
            .finally(() => {
            if (!disposed)
                setLoading(false);
        });
        return () => {
            disposed = true;
        };
    }, [open, existingCollectionId, language, editContext?.itemsRepository]);
    const addToList = useCallback(async (itemsToAdd) => {
        const newItems = [...items];
        const sourceItems = itemsToAdd ?? selectedInTree;
        const nodesToAdd = sourceItems.filter((node) => !newItems.some((x) => x.descriptor.id === node.id));
        const nodesNeedingFetch = nodesToAdd.filter((node) => !node.path || !node.name || !node.displayName);
        if (nodesNeedingFetch.length > 0 && editContext?.itemsRepository) {
            try {
                const descriptorsToFetch = nodesNeedingFetch.map((node) => ({
                    id: node.id,
                    language: node.language || language,
                    version: node.version || 1,
                }));
                const stubs = await editContext.itemsRepository.getItemsStubs(descriptorsToFetch);
                const stubMap = new Map(stubs.map((s) => [s.id, s]));
                nodesToAdd.forEach((node) => {
                    const stub = stubMap.get(node.id);
                    newItems.push({
                        descriptor: {
                            id: node.id,
                            language: node.language || language,
                            version: node.version || 1,
                            name: stub?.name || node.name || "",
                            displayName: stub?.displayName || node.displayName || "",
                            path: stub?.path || node.path || node.idPath || "",
                        },
                        includeSubitems: false,
                    });
                });
            }
            catch (err) {
                console.error("Failed to fetch item stubs:", err);
                nodesToAdd.forEach((node) => {
                    newItems.push({
                        descriptor: {
                            id: node.id,
                            language: node.language || language,
                            version: node.version || 1,
                            name: node.name || "",
                            displayName: node.displayName || "",
                            path: node.path || node.idPath || "",
                        },
                        includeSubitems: false,
                    });
                });
            }
        }
        else {
            nodesToAdd.forEach((node) => {
                newItems.push({
                    descriptor: {
                        id: node.id,
                        language: node.language || language,
                        version: node.version || 1,
                        name: node.name || "",
                        displayName: node.displayName || "",
                        path: node.path || node.idPath || "",
                    },
                    includeSubitems: false,
                });
            });
        }
        setItems(newItems);
        setSelectedInTree([]);
    }, [items, selectedInTree, language, editContext?.itemsRepository]);
    const removeFromList = useCallback(() => {
        const idsToRemove = new Set(selectedFromList.map((i) => i.descriptor.id));
        setItems(items.filter((x) => !idsToRemove.has(x.descriptor.id)));
        setSelectedFromList([]);
    }, [items, selectedFromList]);
    const handleAddItem = useCallback(async (item) => {
        const itemId = "id" in item ? item.id : item.id;
        const exists = items.some((x) => x.descriptor.id === itemId);
        if (!exists) {
            let itemDescriptor = {
                id: itemId,
                language: item.language || language,
                version: item.version ?? 1,
                name: item.name || "",
                displayName: item.displayName || "",
                path: item.path || "",
            };
            if ((!itemDescriptor.path ||
                !itemDescriptor.name ||
                !itemDescriptor.displayName) &&
                editContext?.itemsRepository) {
                try {
                    const stubs = await editContext.itemsRepository.getItemsStubs([
                        {
                            id: itemId,
                            language: itemDescriptor.language,
                            version: itemDescriptor.version,
                        },
                    ]);
                    if (stubs.length > 0 && stubs[0]) {
                        itemDescriptor = {
                            ...itemDescriptor,
                            name: stubs[0].name || itemDescriptor.name,
                            displayName: stubs[0].displayName || itemDescriptor.displayName || "",
                            path: stubs[0].path || itemDescriptor.path || "",
                        };
                    }
                }
                catch (err) {
                    console.error("Failed to fetch item stub:", err);
                }
            }
            setItems([
                ...items,
                {
                    descriptor: itemDescriptor,
                    includeSubitems: false,
                },
            ]);
        }
    }, [items, language, editContext?.itemsRepository]);
    const removeItem = useCallback((index) => {
        setItems((prev) => prev.filter((_, i) => i !== index));
    }, []);
    const toggleSubitems = useCallback((index) => {
        setItems((prev) => prev.map((item, i) => i === index
            ? { ...item, includeSubitems: !item.includeSubitems }
            : item));
    }, []);
    const handleConfirm = useCallback(async () => {
        if (items.length === 0) {
            setError("Add at least one item");
            return;
        }
        setLoading(true);
        setError(null);
        const itemsPayload = items.map((item) => ({
            descriptor: {
                id: item.descriptor.id,
                language: item.descriptor.language ?? language,
                version: item.descriptor.version ?? 1,
            },
            includeSubitems: item.includeSubitems,
        }));
        if (existingCollectionId) {
            const result = await updateItemCollection({
                collectionId: existingCollectionId,
                name: name.trim() || null,
                items: itemsPayload,
            });
            if (result.type === "success" && result.data?.collectionId) {
                resetState();
                onOpenChange(false);
                onConfirm(result.data.collectionId);
            }
            else {
                setError(result.summary || "Failed to update collection");
            }
        }
        else {
            const result = await createItemCollection({
                name: name.trim() || undefined,
                items: itemsPayload,
            });
            if (result.type === "success" && result.data?.collectionId) {
                resetState();
                onOpenChange(false);
                onConfirm(result.data.collectionId);
            }
            else {
                setError(result.summary || "Failed to create collection");
            }
        }
        setLoading(false);
    }, [
        name,
        items,
        language,
        existingCollectionId,
        onConfirm,
        onOpenChange,
        resetState,
    ]);
    const handleCancel = useCallback(() => {
        if (loading)
            return;
        resetState();
        onOpenChange(false);
    }, [loading, resetState, onOpenChange]);
    const handleOpenChange = useCallback((nextOpen) => {
        if (!nextOpen)
            handleCancel();
        else
            onOpenChange(nextOpen);
    }, [handleCancel, onOpenChange]);
    const canConfirm = !loading && items.length > 0;
    return (_jsx(Dialog, { open: open, onOpenChange: handleOpenChange, children: _jsxs(DialogContent, { className: "flex max-w-5xl overflow-hidden border-none p-0 shadow-2xl", style: { height: "85vh", maxHeight: "85vh" }, children: [_jsx(StyledDialogTitle, { icon: _jsx(ClipboardCheck, { strokeWidth: 1 }), title: existingCollectionId
                        ? "Edit Item Collection"
                        : "Create Item Collection" }), _jsxs("div", { className: "flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-6", children: [_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(Label, { htmlFor: "collection-name", children: "Collection name (optional)" }), _jsx(Input, { id: "collection-name", value: name, onChange: (e) => setName(e.target.value), placeholder: "e.g. Product pages for Q1", disabled: loading })] }), _jsxs("div", { className: "flex flex-col gap-3", children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsx(Label, { children: "Items" }), _jsxs("span", { className: "bg-primary/10 text-primary rounded-full px-2.5 py-0.5 text-xs font-semibold", children: [items.length, " selected"] })] }), _jsx(ItemCollectionEditor, { items: items, selectedInTree: selectedInTree, onSelectedInTreeChange: setSelectedInTree, selectedFromList: selectedFromList, onSelectedFromListChange: setSelectedFromList, onAddToList: addToList, onRemoveFromList: removeFromList, onAddItem: handleAddItem, onRemoveItem: removeItem, onToggleSubitems: toggleSubitems, language: language, rootItemIds: rootItemIds, selectedItemsLabel: "Selected Items", emptyMessage: "No items selected", emptyHint: "Browse or search to add items", height: 320, localStorageKey: "item-collection-editor-dialog-splitter" })] }), error ? _jsx("p", { className: "text-destructive text-sm", children: error }) : null] }), _jsxs(DialogButtons, { hideBorder: true, className: "bg-gray-50/50", children: [_jsx(Button, { variant: "ghost", onClick: handleCancel, disabled: loading, children: "Cancel" }), _jsx(Button, { onClick: () => void handleConfirm(), disabled: !canConfirm, className: "min-w-[120px] shadow-sm", children: loading ? (_jsxs(_Fragment, { children: [_jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }), existingCollectionId ? "Saving…" : "Creating…"] })) : existingCollectionId ? ("Save") : ("Create") })] })] }) }));
}
//# sourceMappingURL=ItemCollectionEditorDialog.js.map