"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, 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 { Loader2 } from "lucide-react";
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";
export const TreeSelector = ({ onHide, onMediaSelected, selectedIdPath, language, mode, initialSearchTerm, }) => {
    const [selectedFolderId, setSelectedFolderId] = useState();
    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 [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 path = selectedIdPath.split("/");
            if (path.length > 1) {
                setSelectedFolderId(path[path.length - 2]);
                setSelectedImageId(path[path.length - 1]?.toLowerCase().substring(1, 37));
            }
            setExpandedIdPath(selectedIdPath);
        }
        if (!selectedIdPath) {
            setExpandedIdPath(history[0]?.idPath ?? "3D6658D8-A0BF-4E75-B3E2-D050FABCF4E1");
            setSelectedFolderId(history[0]?.id);
            setSelectedImageId(undefined);
        }
    }, [selectedIdPath]);
    useEffect(() => {
        loadThumbnailsAndSelectImage();
    }, [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 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: [_jsxs("div", { className: "flex items-center justify-between border-b px-4 py-2", children: [_jsx("span", { className: "text-xs font-semibold uppercase tracking-wider text-gray-500", children: "Navigation" }), history.length > 0 && (_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: "h-7 w-7 p-0 hover:bg-gray-200", children: _jsx(ClockIcon, { className: "h-3.5 w-3.5 text-gray-500" }) }) }) }), _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: "mb-1 px-2 py-1.5 text-xs font-semibold text-gray-500", children: "RECENT LOCATIONS" }), history.map((x) => (_jsxs("div", { className: "flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-xs hover:bg-gray-100", onClick: (e) => {
                                            e.stopPropagation();
                                            setSelectedFolderId(x.id);
                                            setExpandedIdPath(x.idPath);
                                            setSearchPrompt(undefined);
                                            setIsPopoverOpen(false);
                                        }, children: [_jsx("div", { className: "h-1.5 w-1.5 rounded-full bg-primary/40" }), _jsx("span", { className: "truncate", children: x.name })] }, x.idPath)))] })] }))] }), _jsx("div", { "data-testid": "media-selector-tree", className: `absolute inset-0 top-10 overflow-auto p-2 ${isPopoverOpen ? "pointer-events-none" : ""}`, children: _jsx(ContentTree, { rootItemIds: ["3D6658D8-A0BF-4E75-B3E2-D050FABCF4E1"], selectionMode: "single", selectedItemIds: selection, templateIds: ["FE5DD826-48C6-436D-B87A-7C4210C7413B"], hideRootNodes: true, onItemInserted: (item) => {
                        setSelectedFolderId(item.id);
                    }, expandIdPath: expandedIdPath ?? "3D6658D8-A0BF-4E75-B3E2-D050FABCF4E1", onSelectionChange: (selection) => {
                        const selectedNode = selection[0];
                        if (selectedNode)
                            setSelectedFolderId(selectedNode.id);
                        else
                            setSelectedFolderId(undefined);
                    }, 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: _jsx(AiImageSearchPrompt, { onSearchPromptChange: searchDebounced, initialValue: initialSearchTerm }) }), _jsxs("div", { className: "relative min-h-0 flex-1 overflow-hidden", 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: "h-8 w-8 animate-spin text-primary/60" }), _jsx("span", { className: "text-xs font-medium text-gray-500", children: "Loading media..." })] }) })), _jsx(Thumbnails, { images: images ?? [], selectedImage: selectedImage, setSelectedImage: setSelectedImage, onMediaSelected: () => {
                            updateHistory();
                            onMediaSelected(selectedImage.id);
                        }, onHide: onHide })] }), selectedFolderId && !editContext?.isMobile && (_jsx("div", { className: "border-t bg-gray-50/50", children: _jsx(UploadZone, { selectedFolderId: selectedFolderId, 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-gray-50/30",
                        content: treePanelContent,
                    },
                    {
                        name: "thumbnails",
                        defaultSize: "auto",
                        className: "bg-white",
                        content: thumbnailsPanelContent,
                    },
                    {
                        name: "preview",
                        defaultSize: 280,
                        hidden: !!editContext?.isMobile && !selectedImage,
                        className: `bg-gray-50/30 ${editContext?.isMobile ? "border-t" : "border-l"}`,
                        content: (_jsx("div", { className: "relative h-full overflow-y-auto", children: _jsx(Preview, { selectedImage: selectedImage }) })),
                    },
                ] }), _jsxs(DialogButtons, { className: `bg-white ${editContext?.isMobile ? "justify-center" : ""}`, children: [!editContext?.isMobile && (_jsx(Button, { variant: "ghost", onClick: () => onHide(), className: "text-gray-500 hover:text-gray-900", children: "Cancel" })), _jsxs(UploadButton, { variant: "outline", auto: true, accept: "image/*,video/*", uploadUrl: "/parhelia/upload?folder=" + selection[0], onUpload: async (uploadResponse) => {
                            updateHistory();
                            const response = JSON.parse(uploadResponse.xhr.responseText);
                            const thumbs = await loadThumbnails(selectedFolderId);
                            setSelectedImage(thumbs?.find((x) => x.id === response.id));
                        }, className: "gap-2", children: [_jsx(Upload, { className: "h-4 w-4" }), " Upload New"] }), _jsx(Button, { disabled: !selectedImage, onClick: () => {
                            updateHistory();
                            onMediaSelected(selectedImage.id);
                            onHide();
                        }, className: "min-w-[100px] shadow-sm", children: "Select Media" })] })] }));
};
//# sourceMappingURL=TreeSelector.js.map