"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import ContentTree from "../ContentTree";
import { Splitter } from "../ui/Splitter";
import { useEffect, useState, useRef, } from "react";
import { getChildren } from "../services/contentService";
import { useEditContext } from "../client/editContext";
import { Button } from "../../components/ui/button";
import { UploadButton } from "../../components/ui/upload-button";
import { executeSearch } from "../services/searchService";
import { ClockIcon, Grid3X3, List, Loader2, Upload } from "lucide-react";
import DialogButtons from "../ui/DialogButtons";
import { Thumbnails } from "./Thumbnails";
import { Preview } from "./Preview";
import { UploadZone } from "./UploadZone";
import { AiImageSearchPrompt } from "./AiImageSearchPrompt";
import { useDebouncedCallback } from "use-debounce";
import { Popover, PopoverTrigger, PopoverContent, } from "../../components/ui/popover";
import { Tooltip, TooltipTrigger, TooltipContent, } from "../../components/ui/tooltip";
import { localStorageService } from "../services/localStorageService";
import { toast } from "sonner";
import { normalizeMediaSelectionId, parseMediaSelectionIdPath, } from "./mediaSelectionPath";
import { replaceMediaItemWithFile, uploadMediaFiles } from "./mediaUpload";
import { SimpleIconButton } from "../ui/SimpleIconButton";
// Stable references so the ContentTree useEffect (which depends on rootItemIds
// and templateIds) does not refire on every parent render. Inline literals
// would create new arrays each render, racing ContentTree's preLoadNodes
// version counter and occasionally dropping a valid tree response on the floor.
const MEDIA_ROOT_ITEM_IDS = ["3D6658D8-A0BF-4E75-B3E2-D050FABCF4E1"];
const MEDIA_FOLDER_TEMPLATE_IDS = ["FE5DD826-48C6-436D-B87A-7C4210C7413B"];
export const TreeSelector = ({ onHide, onMediaSelected, selectedIdPath, language, mode, initialSearchTerm, }) => {
    const [selectedFolderId, setSelectedFolderId] = useState();
    const [selectedFolderCanCreate, setSelectedFolderCanCreate] = useState(false);
    const [images, setImages] = useState();
    const [selectedImage, setSelectedImage] = useState();
    const [selectedImageId, setSelectedImageId] = useState();
    const [expandedIdPath, setExpandedIdPath] = useState();
    const [searchPrompt, setSearchPrompt] = useState(initialSearchTerm);
    const [loadingThumbnails, setLoadingThumbnails] = useState(false);
    const [uploadingDroppedFiles, setUploadingDroppedFiles] = useState(false);
    const [thumbnailViewMode, setThumbnailViewMode] = useState("grid");
    const [isPopoverOpen, setIsPopoverOpen] = useState(false);
    const historyButtonRef = useRef(null);
    const initialSearchTriggeredRef = useRef(false);
    const selection = selectedFolderId ? [selectedFolderId] : [];
    const editContext = useEditContext();
    const [history, setHistory] = useState(() => {
        return localStorageService.getOrSetItem("editor.mediahistory", []);
    });
    useEffect(() => {
        if (selectedIdPath) {
            const { folderId, mediaId } = parseMediaSelectionIdPath(selectedIdPath);
            if (folderId) {
                setSelectedFolderId(folderId);
                setSelectedImageId(mediaId);
            }
            setExpandedIdPath(selectedIdPath);
        }
        if (!selectedIdPath) {
            setExpandedIdPath(history[0]?.idPath ?? "3D6658D8-A0BF-4E75-B3E2-D050FABCF4E1");
            setSelectedFolderId(normalizeMediaSelectionId(history[0]?.id));
            setSelectedImageId(undefined);
        }
    }, [selectedIdPath]);
    useEffect(() => {
        void loadThumbnailsAndSelectImage();
    }, [selectedFolderId, selectedImageId]);
    useEffect(() => {
        if (!selectedFolderId || !editContext?.itemsRepository) {
            setSelectedFolderCanCreate(false);
            return;
        }
        let cancelled = false;
        editContext.itemsRepository
            .getItem({
            id: selectedFolderId,
            language: "en",
            version: 0,
        })
            .then((item) => {
            if (!cancelled) {
                setSelectedFolderCanCreate(item?.canCreate ?? false);
            }
        })
            .catch(() => {
            if (!cancelled) {
                setSelectedFolderCanCreate(false);
            }
        });
        return () => {
            cancelled = true;
        };
    }, [editContext?.itemsRepository, selectedFolderId]);
    const updateHistory = async () => {
        if (!selectedFolderId)
            return;
        const item = await editContext?.itemsRepository.getItem({
            id: selectedFolderId,
            language: "en",
            version: 0,
        });
        setHistory((history) => {
            if (!item?.idPath || !item.name)
                return history;
            const newEntry = {
                name: item.name,
                id: item.id,
                idPath: item?.idPath,
            };
            const newHistory = [
                newEntry,
                ...history.filter((x) => x.idPath !== newEntry.idPath).slice(0, 4),
            ];
            localStorageService.setItem("editor.mediahistory", newHistory);
            return newHistory;
        });
    };
    async function loadThumbnailsAndSelectImage() {
        setSelectedImage(undefined);
        setImages([]);
        const images = await loadThumbnails(selectedFolderId);
        if (selectedImageId)
            setSelectedImage(images?.find((x) => x.id === selectedImageId));
    }
    async function loadThumbnails(selectedFolderId) {
        if (searchPrompt) {
            await search(searchPrompt);
            return;
        }
        if (!selectedFolderId)
            setImages([]);
        else {
            setLoadingThumbnails(true);
            const children = await getChildren(selectedFolderId, editContext.sessionId, mode === "video"
                ? [
                    "e76adbdf-87d1-4fcb-ba71-274f7dbf5670",
                    "374d3a99-c098-4cd2-8fbc-dc2d1ca1c904",
                ]
                : [
                    "C97BA923-8009-4858-BDD5-D8BE5FCCECF7",
                    "F1828A2C-7E5D-4BBD-98CA-320474871548",
                ], false, language);
            setImages(children);
            setLoadingThumbnails(false);
            return children;
        }
    }
    const isFileDrag = (event) => Array.from(event.dataTransfer.types).includes("Files");
    const uploadSelectedFiles = async (files) => {
        if (!selectedFolderId || files.length === 0)
            return;
        if (!selectedFolderCanCreate) {
            toast.error("You don't have permission to upload to this folder.");
            return;
        }
        try {
            setUploadingDroppedFiles(true);
            const uploaded = await uploadMediaFiles({
                files,
                folderId: selectedFolderId,
                editContext,
                language,
            });
            if (uploaded.length > 0) {
                void updateHistory();
                const selectedId = uploaded[uploaded.length - 1]?.id;
                const thumbs = await loadThumbnails(selectedFolderId);
                setSelectedImageId(selectedId);
                setSelectedImage(thumbs?.find((x) => x.id === selectedId));
            }
        }
        catch (error) {
            console.error("Error uploading files:", error);
            toast.error("Failed to upload files. Please try again.");
        }
        finally {
            setUploadingDroppedFiles(false);
        }
    };
    const replaceMediaFile = async (image, file) => {
        try {
            setUploadingDroppedFiles(true);
            const result = await replaceMediaItemWithFile({
                file,
                mediaItem: image,
                editContext,
                language,
            });
            if (result) {
                const selectedId = result.id || image.id;
                const thumbs = await loadThumbnails(selectedFolderId);
                setSelectedImageId(selectedId);
                setSelectedImage(thumbs?.find((x) => x.id === selectedId) || image);
            }
        }
        finally {
            setUploadingDroppedFiles(false);
        }
    };
    const handleThumbnailDragOver = (event) => {
        if (!isFileDrag(event))
            return;
        event.preventDefault();
        event.stopPropagation();
        event.dataTransfer.dropEffect =
            selectedFolderId && selectedFolderCanCreate && !uploadingDroppedFiles
                ? "copy"
                : "none";
    };
    const handleThumbnailDrop = (event) => {
        if (!isFileDrag(event))
            return;
        event.preventDefault();
        event.stopPropagation();
        if (!selectedFolderId) {
            toast.error("Select a media folder before uploading.");
            return;
        }
        const files = Array.from(event.dataTransfer.files);
        void uploadSelectedFiles(files);
    };
    const searchDebounced = useDebouncedCallback(async (searchPrompt) => {
        return search(searchPrompt);
    }, 300);
    const search = async (searchPrompt) => {
        if (!editContext)
            return;
        setSearchPrompt(searchPrompt);
        if (searchPrompt.length == 0)
            return;
        setLoadingThumbnails(true);
        const result = await executeSearch({
            query: searchPrompt,
            rootItemIds: selectedFolderId ? [selectedFolderId] : undefined,
            editContext,
            maxResults: 50,
            index: "media",
            skipValidation: true,
        });
        if (result.type == "success") {
            setImages(result.data);
        }
        else {
            toast.error(result.response.statusText || "Error searching");
        }
        setLoadingThumbnails(false);
    };
    // Trigger search when initialSearchTerm is provided
    useEffect(() => {
        if (initialSearchTerm &&
            !initialSearchTriggeredRef.current &&
            editContext) {
            initialSearchTriggeredRef.current = true;
            if (initialSearchTerm.trim()) {
                search(initialSearchTerm);
            }
        }
    }, [initialSearchTerm, editContext]);
    const treePanelContent = (_jsxs("div", { className: `relative flex h-full flex-col ${editContext?.isMobile ? "border-b" : "border-r"}`, children: [history.length > 0 && (_jsx("div", { className: "absolute top-2 right-2 z-20", children: _jsxs(Popover, { open: isPopoverOpen, enableIframeClickDetection: false, onOpenChange: setIsPopoverOpen, children: [_jsxs(Tooltip, { children: [_jsx(PopoverTrigger, { asChild: true, children: _jsx(TooltipTrigger, { asChild: true, children: _jsx(Button, { ref: historyButtonRef, variant: "ghost", size: "sm", className: "hover:bg-neutral-grey-10 h-7 w-7 p-0", children: _jsx(ClockIcon, { className: "text-neutral-grey-50 h-3.5 w-3.5" }) }) }) }), _jsx(TooltipContent, { children: "Recent Locations" })] }), _jsxs(PopoverContent, { className: "pointer-events-auto z-110 w-64 p-1 shadow-lg", onInteractOutside: (e) => {
                                // Prevent closing when clicking the trigger button
                                const target = e.target;
                                const isTriggerButton = historyButtonRef.current?.contains(target) ||
                                    historyButtonRef.current === target;
                                if (isTriggerButton) {
                                    e.preventDefault();
                                }
                            }, onPointerDown: (e) => e.stopPropagation(), onPointerMove: (e) => e.stopPropagation(), onPointerEnter: (e) => e.stopPropagation(), onPointerLeave: (e) => e.stopPropagation(), onClick: (e) => e.stopPropagation(), onMouseDown: (e) => e.stopPropagation(), onMouseMove: (e) => e.stopPropagation(), onMouseEnter: (e) => e.stopPropagation(), onMouseLeave: (e) => e.stopPropagation(), children: [_jsx("div", { className: "text-neutral-grey-50 mb-1 px-2 py-1.5 text-xs font-medium", children: "Recent locations" }), history.map((x) => (_jsxs("div", { className: "hover:bg-neutral-grey-5 flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-xs", onClick: (e) => {
                                        e.stopPropagation();
                                        setSelectedFolderId(normalizeMediaSelectionId(x.id));
                                        setExpandedIdPath(x.idPath);
                                        setSelectedImageId(undefined);
                                        setSearchPrompt(undefined);
                                        setIsPopoverOpen(false);
                                    }, children: [_jsx("div", { className: "bg-primary/40 h-1.5 w-1.5 rounded-full" }), _jsx("span", { className: "truncate", children: x.name })] }, x.idPath)))] })] }) })), _jsx("div", { "data-testid": "media-selector-tree", className: `absolute inset-0 overflow-auto p-2 ${isPopoverOpen ? "pointer-events-none" : ""}`, children: _jsx(ContentTree, { rootItemIds: MEDIA_ROOT_ITEM_IDS, selectionMode: "single", selectedItemIds: selection, templateIds: MEDIA_FOLDER_TEMPLATE_IDS, hideRootNodes: true, onItemInserted: (item) => {
                        setSelectedFolderId(normalizeMediaSelectionId(item.id));
                        setSelectedImageId(undefined);
                        setSelectedFolderCanCreate(item.canCreate ?? false);
                    }, expandIdPath: expandedIdPath ?? "3D6658D8-A0BF-4E75-B3E2-D050FABCF4E1", onSelectionChange: (selection) => {
                        const selectedNode = selection[0];
                        if (selectedNode) {
                            setSelectedFolderId(normalizeMediaSelectionId(selectedNode.id));
                            setSelectedImageId(undefined);
                            setSelectedFolderCanCreate(selectedNode.canCreate ?? false);
                        }
                        else {
                            setSelectedFolderId(undefined);
                            setSelectedFolderCanCreate(false);
                        }
                    }, language: language }) })] }));
    const thumbnailsPanelContent = (_jsxs("div", { className: "relative flex h-full w-full flex-col", children: [_jsx("div", { className: "border-b bg-white p-2", children: _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("div", { className: "min-w-0 flex-1", children: _jsx(AiImageSearchPrompt, { onSearchPromptChange: searchDebounced, initialValue: initialSearchTerm }) }), _jsxs("div", { className: "flex shrink-0 gap-1", children: [_jsx(SimpleIconButton, { icon: _jsx(Grid3X3, { className: "h-6 w-6 p-1", strokeWidth: 1 }), label: "Grid View", size: "large", selected: thumbnailViewMode === "grid", "data-testid": "media-selector-grid-view", onClick: () => setThumbnailViewMode("grid") }), _jsx(SimpleIconButton, { icon: _jsx(List, { className: "h-6 w-6 p-1", strokeWidth: 1 }), label: "List View", size: "large", selected: thumbnailViewMode === "list", "data-testid": "media-selector-list-view", onClick: () => setThumbnailViewMode("list") })] })] }) }), _jsxs("div", { className: "relative min-h-0 flex-1 overflow-hidden", onDragOver: handleThumbnailDragOver, onDrop: handleThumbnailDrop, children: [loadingThumbnails && (_jsx("div", { className: "absolute inset-0 z-10 flex items-center justify-center bg-white/50 backdrop-blur-[1px]", children: _jsxs("div", { className: "flex flex-col items-center gap-2", children: [_jsx(Loader2, { className: "text-primary/60 h-8 w-8 animate-spin" }), _jsx("span", { className: "text-neutral-grey-50 text-xs font-medium", children: "Loading media..." })] }) })), _jsx(Thumbnails, { images: images ?? [], selectedImage: selectedImage, setSelectedImage: setSelectedImage, onMediaSelected: (mediaId) => {
                            updateHistory();
                            onMediaSelected(mediaId);
                        }, onHide: onHide, language: language, viewMode: thumbnailViewMode, loading: loadingThumbnails, onReplaceMedia: (image, file) => {
                            void replaceMediaFile(image, file);
                        } })] }), selectedFolderId && !editContext?.isMobile && (_jsx("div", { className: "bg-neutral-grey-5/50 border-t", children: _jsx(UploadZone, { selectedFolderId: selectedFolderId, canCreate: selectedFolderCanCreate, uploadFiles: uploadSelectedFiles, uploadCompleted: () => {
                        loadThumbnailsAndSelectImage();
                    } }) }))] }));
    return (_jsxs(_Fragment, { children: [_jsx(Splitter, { className: "flex-1 overflow-hidden", direction: editContext?.isMobile ? "vertical" : "horizontal", localStorageKey: editContext?.isMobile
                    ? "editor.mediaSelectorTreeSizeMobile"
                    : "editor.mediaSelectorTreeSize", panels: [
                    {
                        name: "tree",
                        defaultSize: 300,
                        className: "bg-neutral-grey-5/30",
                        content: treePanelContent,
                    },
                    {
                        name: "thumbnails",
                        defaultSize: "auto",
                        className: "bg-white",
                        content: thumbnailsPanelContent,
                    },
                    {
                        name: "preview",
                        defaultSize: 280,
                        hidden: !!editContext?.isMobile && !selectedImage,
                        className: `bg-neutral-grey-5/30 ${editContext?.isMobile ? "border-t" : "border-l"}`,
                        content: (_jsx("div", { className: "relative h-full overflow-y-auto", children: _jsx(Preview, { selectedImage: selectedImage, onReplaceMedia: (image, file) => {
                                    void replaceMediaFile(image, file);
                                } }) })),
                    },
                ] }), _jsxs(DialogButtons, { className: `bg-white ${editContext?.isMobile ? "justify-center" : ""}`, children: [!editContext?.isMobile && (_jsx(Button, { variant: "ghost", onClick: () => onHide(), className: "text-neutral-grey-50 hover:text-neutral-grey-100", children: "Cancel" })), _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("span", { children: _jsxs(UploadButton, { variant: "outline", size: "lg", accept: "image/*,video/*", disabled: !selectedFolderId || !selectedFolderCanCreate, onFileSelect: (files) => {
                                            void uploadSelectedFiles(Array.from(files));
                                        }, className: "gap-2", children: [_jsx(Upload, { className: "h-4 w-4" }), " Upload New"] }) }) }), selectedFolderId && !selectedFolderCanCreate && (_jsx(TooltipContent, { children: "You don't have permission to upload to this folder." }))] }), _jsx(Button, { disabled: !selectedImage, onClick: () => {
                            updateHistory();
                            onMediaSelected(selectedImage.id);
                            onHide();
                        }, className: "min-w-[100px] shadow-sm", children: "Select Media" })] })] }));
};
//# sourceMappingURL=TreeSelector.js.map