import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { ImageRenditionFormat } from "@vertesia/common";
import { Button, Spinner, useToast } from "@vertesia/ui/core";
import { useNavigate } from "@vertesia/ui/router";
import { useUserSession } from "@vertesia/ui/session";
import { JSONDisplay, MarkdownRenderer } from "@vertesia/ui/widgets";
import { ChevronRight, Download, FileText, Info, LayoutGrid, Maximize2, X, } from "lucide-react";
import { useEffect, useState } from "react";
export function DocumentPreviewPanel({ objectId, isOpen, onClose, }) {
    const navigate = useNavigate();
    const { client, store } = useUserSession();
    const [object, setObject] = useState(null);
    const [isLoading, setIsLoading] = useState(false);
    const [loadingText, setLoadingText] = useState(false);
    const [text, setText] = useState();
    const [imageUrl, setImageUrl] = useState();
    const [currentTab, setCurrentTab] = useState("preview");
    const toast = useToast();
    useEffect(() => {
        if (objectId && isOpen) {
            setIsLoading(true);
            store.objects
                .retrieve(objectId, "+embeddings")
                .then((result) => {
                setObject(result);
                // If the object has text, use it
                if (result.text) {
                    setText(result.text);
                }
                else {
                    // Otherwise, fetch text
                    loadObjectText(result.id);
                }
                // If it's an image, load the image URL
                const content = result.content;
                const isImage = content &&
                    content.source &&
                    content.type &&
                    content.type.startsWith("image/");
                if (isImage) {
                    loadImageUrl(result);
                }
            })
                .catch((error) => {
                console.error("Error loading object:", error);
                toast({
                    title: "Error",
                    description: "Failed to load document",
                    status: "error",
                    duration: 3000,
                });
            })
                .finally(() => {
                setIsLoading(false);
            });
        }
        else {
            // Reset state when panel closes
            setObject(null);
            setText(undefined);
            setImageUrl(undefined);
        }
    }, [objectId, isOpen, store.objects]);
    const loadObjectText = async (id) => {
        setLoadingText(true);
        try {
            const result = await store.objects.getObjectText(id);
            setText(result.text);
        }
        catch (error) {
            console.error("Error loading text:", error);
        }
        finally {
            setLoadingText(false);
        }
    };
    const loadImageUrl = async (obj) => {
        try {
            // Try to get a rendition first
            const rendition = await client.objects.getRendition(obj.id, {
                format: ImageRenditionFormat.jpeg,
                generate_if_missing: false,
            });
            // Don't use rendition object to avoid type issues
            if (rendition.status === "found") {
                console.log("Found rendition");
            }
            // Get download URL
            const downloadUrlResult = await client.files.getDownloadUrl(obj.content.source);
            setImageUrl(downloadUrlResult.url);
        }
        catch (error) {
            console.error("Error loading image:", error);
        }
    };
    const handleViewFullDocument = () => {
        if (object) {
            navigate(`/legal/objects/${object.id}`);
            onClose();
        }
    };
    const seemsMarkdown = text &&
        (text.startsWith("#") || text.includes("\n#") || text.includes("\n*"));
    const isImage = object?.content?.type && object.content.type.startsWith("image/");
    const isPdf = object?.content?.type === "application/pdf";
    if (!isOpen)
        return null;
    return (_jsxs("div", { className: `fixed inset-y-0 right-0 w-2/5 dark:bg-slate-900 shadow-xl z-50 flex flex-col transition-transform duration-300 transform ${isOpen ? "translate-x-0" : "translate-x-full"}`, children: [_jsxs("div", { className: "flex items-center justify-between px-4 py-3 border-b dark:border-gray-700 bg-gradient-to-r from-indigo-50 to-gray-50 dark:from-gray-800 dark:to-gray-900", children: [_jsxs("div", { className: "flex items-center", children: [_jsx(FileText, { className: "h-5 w-5 text-indigo-600 mr-2" }), _jsx("h2", { className: "text-lg font-semibold text-gray-800 dark:text-gray-200 truncate", children: isLoading
                                    ? "Loading document..."
                                    : object?.name || "Document Preview" })] }), _jsxs("div", { className: "flex items-center space-x-2", children: [_jsxs(Button, { variant: "ghost", size: "sm", onClick: handleViewFullDocument, className: "flex items-center gap-1 text-indigo-600 hover:text-indigo-800", children: [_jsx(Maximize2, { className: "h-4 w-4" }), _jsx("span", { children: "Full View" })] }), _jsx(Button, { variant: "ghost", size: "sm", onClick: onClose, className: "flex items-center text-gray-600 hover:text-gray-800 dark:text-gray-300 dark:hover:text-gray-100", children: _jsx(X, { className: "h-5 w-5" }) })] })] }), isLoading ? (_jsx("div", { className: "flex-1 flex items-center justify-center", children: _jsxs("div", { className: "text-center", children: [_jsx(Spinner, { size: "lg", className: "text-indigo-600 dark:text-indigo-400 mb-2" }), _jsx("p", { className: "text-gray-600 dark:text-gray-400", children: "Loading document..." })] }) })) : (_jsxs("div", { className: "flex-1 flex flex-col h-full", children: [_jsx("div", { className: "border-b", children: _jsxs("div", { className: "flex px-4", children: [_jsx("button", { className: `py-2 px-4 font-medium border-b-2 ${currentTab === "preview"
                                        ? "border-indigo-600 text-indigo-700 dark:text-indigo-300"
                                        : "border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"}`, onClick: () => setCurrentTab("preview"), children: _jsxs("div", { className: "flex items-center gap-1", children: [_jsx(LayoutGrid, { className: "h-4 w-4" }), _jsx("span", { children: "Preview" })] }) }), _jsx("button", { className: `py-2 px-4 font-medium border-b-2 ${currentTab === "properties"
                                        ? "border-indigo-600 text-indigo-700 dark:text-indigo-300"
                                        : "border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"}`, onClick: () => setCurrentTab("properties"), children: _jsxs("div", { className: "flex items-center gap-1", children: [_jsx(Info, { className: "h-4 w-4" }), _jsx("span", { children: "Properties" })] }) })] }) }), _jsxs("div", { className: "flex-1 overflow-auto p-4", children: [currentTab === "preview" && (_jsxs("div", { className: "h-full", children: [loadingText ? (_jsx("div", { className: "flex items-center justify-center h-40", children: _jsx(Spinner, { size: "md", className: "text-indigo-600 dark:text-indigo-400" }) })) : text ? (_jsx("div", { className: "shadow rounded-md p-4 border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800", children: seemsMarkdown ? (_jsx("div", { className: "prose prose-sm max-w-none prose-p:my-2 prose-pre:bg-gray-800 prose-pre:my-2 prose-headings:text-indigo-700 dark:prose-invert dark:prose-headings:text-indigo-300", children: _jsx(MarkdownRenderer, { children: text }) })) : (_jsx("pre", { className: "text-wrap whitespace-pre-wrap dark:text-gray-200", children: text })) })) : null, isImage && (_jsx("div", { className: "mt-4", children: imageUrl ? (_jsx("div", { className: "border border-gray-200 dark:border-gray-700 rounded-md p-2 bg-white dark:bg-gray-800", children: _jsx("img", { src: imageUrl, alt: object?.name, className: "mx-auto max-h-[70vh] object-contain" }) })) : (_jsx("div", { className: "flex items-center justify-center h-40", children: _jsx(Spinner, { size: "md", className: "text-indigo-600 dark:text-indigo-400" }) })) })), isPdf && (_jsxs("div", { className: "flex flex-col items-center justify-center h-64 border border-gray-200 dark:border-gray-700 rounded-md p-4 bg-gray-50 dark:bg-gray-800", children: [_jsx(FileText, { className: "h-16 w-16 text-indigo-300 dark:text-indigo-400 mb-4" }), _jsxs("p", { className: "text-gray-600 dark:text-gray-400 text-center mb-4", children: ["PDF document preview is available in full view. TODO", " "] }), _jsx(Button, { onClick: handleViewFullDocument, className: "bg-indigo-600 hover:bg-indigo-700 text-white", children: "Open Full Document View" })] })), !isImage && !text && !isPdf && !loadingText && (_jsxs("div", { className: "flex flex-col items-center justify-center h-64 border border-gray-200 dark:border-gray-700 rounded-md p-4 bg-gray-50 dark:bg-gray-800", children: [_jsx(FileText, { className: "h-16 w-16 text-gray-300 dark:text-gray-600 mb-4" }), _jsx("p", { className: "text-gray-600 dark:text-gray-400 text-center", children: "No preview available for this document type." })] }))] })), currentTab === "properties" && object && (_jsxs("div", { className: "h-full", children: [object.properties ? (_jsx("div", { className: "shadow rounded-md p-4 border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800", children: _jsx(JSONDisplay, { value: object.properties }) })) : (_jsxs("div", { className: "flex flex-col items-center justify-center h-64 border border-gray-200 dark:border-gray-700 rounded-md p-4 bg-gray-50 dark:bg-gray-800", children: [_jsx(Info, { className: "h-16 w-16 text-gray-300 dark:text-gray-600 mb-4" }), _jsx("p", { className: "text-gray-600 dark:text-gray-400 text-center", children: "No properties available for this document." })] })), _jsxs("div", { className: "mt-4", children: [_jsx("h3", { className: "text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2", children: "Document Information" }), _jsx("div", { className: "shadow rounded-md p-4 border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800", children: _jsxs("div", { className: "grid grid-cols-2 gap-y-2 gap-x-4 text-sm", children: [_jsx("div", { className: "text-gray-500 dark:text-gray-400", children: "ID" }), _jsx("div", { className: "font-medium dark:text-gray-200", children: object.id }), _jsx("div", { className: "text-gray-500 dark:text-gray-400", children: "Type" }), _jsx("div", { className: "font-medium dark:text-gray-200", children: object.type?.name || "Unknown" }), _jsx("div", { className: "text-gray-500 dark:text-gray-400", children: "Content Type" }), _jsx("div", { className: "font-medium dark:text-gray-200", children: object.content?.type || "N/A" }), _jsx("div", { className: "text-gray-500", children: "Size" }), _jsx("div", { className: "font-medium", children: object.content && "size" in object.content
                                                                ? formatFileSize(object.content.size)
                                                                : "Unknown" }), _jsx("div", { className: "text-gray-500", children: "Created" }), _jsx("div", { className: "font-medium", children: object.created_at
                                                                ? new Date(object.created_at).toLocaleString()
                                                                : "N/A" }), _jsx("div", { className: "text-gray-500", children: "Updated" }), _jsx("div", { className: "font-medium", children: object.updated_at
                                                                ? new Date(object.updated_at).toLocaleString()
                                                                : "N/A" })] }) })] })] }))] })] })), _jsxs("div", { className: "flex items-center justify-between p-4 border-t bg-gray-50 dark:bg-gray-800 dark:border-gray-700", children: [_jsx("div", { children: object?.content?.source && (_jsxs(Button, { onClick: () => {
                                if (object?.content?.source) {
                                    client.files
                                        .getDownloadUrl(object.content.source)
                                        .then((result) => {
                                        window.open(result.url, "_blank");
                                    })
                                        .catch((error) => {
                                        console.error("Error getting download URL:", error);
                                        toast({
                                            title: "Error",
                                            description: "Failed to download file",
                                            status: "error",
                                            duration: 3000,
                                        });
                                    });
                                }
                            }, variant: "outline", className: "text-indigo-600 border-indigo-300 hover:bg-indigo-50", children: [_jsx(Download, { className: "h-4 w-4 mr-2" }), "Download"] })) }), _jsxs(Button, { onClick: handleViewFullDocument, className: "bg-indigo-600 hover:bg-indigo-700 text-white", children: ["Open Full Document", _jsx(ChevronRight, { className: "h-4 w-4 ml-2" })] })] })] }));
}
function formatFileSize(bytes) {
    if (bytes === 0)
        return "0 Bytes";
    const k = 1024;
    const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
}
//# sourceMappingURL=DocumentPreviewPanel.js.map